You can just use the 3 argument form of np.where for this:

>>> import numpy as np
>>> x = np.array([1,2,31,32,4,0,3,0,0,0])
>>> z = np.array([99] * len(x))
>>> y = np.where(x != 0, x, z)
>>> y
array([ 1,  2, 31, 32,  4, 99,  3, 99, 99, 99])
Answer from mgilson on Stack Overflow
🌐
CSDN
devpress.csdn.net › python › 630452787e66823466199c6f.html
Overlay an image segmentation with numpy and matplotlib_python_Mangs-Python
August 23, 2022 - Both are numpy arrays of (512,512) Image1 = readimage(path) Image2 = readimage(path) # Create image 2 mask mask = ma.masked_where(Image2>0, Image2) Image2_mask = ma.masked_array(Image2,mask) # Plot images plt.figure(dpi=300) y, x = np.mgrid[1:513,1:513] plt.axes().set_aspect('equal', 'datalim') plt.set_cmap(plt.gray()) plt.pcolormesh(x, y, Image1,cmap='gray') plt.pcolormesh(x, y, Image2_mask,cmap='jet') plt.axis([x.min(), x.max(), y.min(), y.max()]) plt.colorbar() plt.show()
🌐
Echochamber
echochamber.me › viewtopic.php
Python + numpy: merging 2d arrays - xkcd
Hi all, So I have a set of 2 ... need to overlay, and then take the maximum of all of them. For example, if I had [[0,1],[2,3],[4,5]] and [[6,5,4],[3,2,1]], then the result should be [[6,5,4],[3,3,1],[4,5,0*]], where 0* could be anything really (zero would be fine, but in practice these shapes of arrays won't ever come up). Using numpy, I wrote the ...
Top answer
1 of 1
1

Because you are limited to writing contiguous blocks of data to GDAL rasters, the best way around this is to create the output array first, then write the array to the output raster. Using this method, you can use numpy's boolean indexing to dictate what is written. Your last for loop would work as follows using this logic:

import numpy

no_data = -2147483647
output_array = numpy.full((newheight, newwidth), no_data, 'int32')

for f in files:
    raster = gdal.Open(f, GA_ReadOnly)
    f_xmin, f_pwidth, f_xskew, f_ymax, f_yskew, f_pheight = raster.GetGeoTransform()
    cols = raster.RasterXSize
    rows = raster.RasterYSize
    xoffset = int((f_xmin - xmin) / f_pwidth)
    yoffset = int((f_ymax - ymax) / f_pheight)  # Assumes grids align
    band = raster.GetRasterBand(1)
    data = band.ReadAsArray()
    # Create a boolean array that allows data where they exist
    mask = (output_array == no_data) & (data != band.GetNoDataValue())  # Note: this assumes you prefer data in order based on the files list
    # Allocate data to output array
    output_array[yoffset:yoffset + rows, xoffset:xoffset + cols][mask] = data[mask]

# Write data to the output raster
outband.WriteArray(output_array)
outband.FlushCache()

However, you will need to fully load the raster in to memory prior to flushing it to the disk. If memory-management is an issue, you can either use numpy.memmap, or read the overlapping block from the output raster for each iteration, which would look like this:

for f in files:
    raster = gdal.Open(f, GA_ReadOnly)
    f_xmin, f_pwidth, f_xskew, f_ymax, f_yskew, f_pheight = raster.GetGeoTransform() #geotransform for the old files being iterated over
    cols = raster.RasterXSize
    rows = raster.RasterYSize
    xoffset = int((f_xmin - xmin) / f_pwidth)
    yoffset = int((f_ymax - ymax) / f_pheight)
    band = raster.GetRasterBand(1)
    data = band.ReadAsArray(0, 0, cols, rows)
    data_update = outband.ReadAsArray(xoffset, yoffset, cols, rows)
    mask = (data_update == no_data) & (data != band.GetNoDataValue())
    data_update[mask] = data[mask]
    outband.WriteArray(data_update, xoffset, yoffset)
    outband.FlushCache()

One last general note of caution: your method assumes that raster grids and data types align.

🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.intersect1d.html
numpy.intersect1d — NumPy v2.5 Manual
>>> import numpy as np >>> np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1]) array([1, 3]) To intersect more than two arrays, use functools.reduce:
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 11524896 › overlay-nd-array-at-different-locations-in-python
numpy - Overlay nd array at different locations in python - Stack Overflow
arr2 = np.zeros((100,100,100),float) for each point I will mannualy find and copy over arr2[minx:maxx,miny:maxy,minz,maxz] = arr1[minx:maxx,miny:maxy,minz,maxz] where min and max are index of the arrays. Yes I am trying to convolve this kernel to the points. I looked into numpy.convolve but don't know how I would go about doing it with scipy.
🌐
TutorialsPoint
tutorialspoint.com › overlay-an-image-segmentation-with-numpy-and-matplotlib
Overlay an image segmentation with Numpy and Matplotlib
Mask an array where a condition is met, to get the masked data. Create a new figure or activate an existing figure using figure() mrthod. Use imshow() method to display data as an image, i.e., on a 2D regular raster. To display the figure, use show() method. from matplotlib import pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True mask = np.zeros((10, 10)) mask[3:-3, 3:-3] = 1 im = mask + np.random.randn(10, 10) * 0.01 masked = np.ma.masked_where(mask == 0, mask) plt.figure() plt.subplot(1, 2, 1) plt.imshow(im, 'gray', interpolation='none') plt.subplot(1, 2, 2) plt.imshow(im, 'gray', interpolation='none') plt.imshow(masked, 'jet', interpolation='none', alpha=0.7) plt.show()
🌐
Moonbooks
moonbooks.org › Articles › How-to-overlay--superimpose-two-images-using-python-and-pillow-
How to overlay / superimpose two images using python and pillow ?
August 24, 2022 - To overlay two images in python, a solution is to use the pillow function paste(), example: from PIL import Image import numpy as np img = Image.open("data_mask_1354_2030.png") background = Image.open("background_1354_2030.png") background.paste(img, (0, 0), img) background.save('how_to_su...
🌐
Readthedocs
pynq.readthedocs.io › en › v2.1 › overlay_design_methodology › python_overlay_api.html
Python Overlay API — Python productivity for Zynq (Pynq) v1.0
from pynq import DefaultOverlay ... using DMA engines or HLS IP with AXI master interfaces. In PYNQ the Xlnk class provides a mechanism to acquire numpy arrays allocated as to be physically contiguous....
Top answer
1 of 2
2

Your issue is trying to work with lists or object arrays.

Numpy is simply not designed for that. Use a flat array instead.

# convert subixs to a flat array
flat_subixs = np.concatenate(subixs)
# compute the lengths once
lengths = np.array([len(l) for l in subixs])
arr = np.repeat(overlay, lengths)
print(arr)

msk = (overlay == 1) | (overlay == 3)
arr[flat_subixs[np.repeat(msk, lengths)]] = np.repeat([44, 48, 47], lengths[msk])
print(arr)

Output:

[0 0 0 0 1 1 1 4 3]
[ 0  0  0  0 44 44 48  4 47]

This way all the slow computations (concatenation and lengths) are performed only once, and all other operations are vectorized.

If you want to mutate overlay this is also possible, just create arr once in the end:

msk = (overlay == 1) | (overlay == 3)
overlay[msk] = [44, 48, 47]
# eventually add other transforms here

# finally create "arr" once
arr = np.repeat(overlay, lengths)
print(arr)
# [ 0  0  0  0 44 44 48  4 47]
2 of 2
-2
import numpy as np

new_value = [44, 48, 47]
msk = (overlay == 1) | (overlay == 3)
overlay[msk] = new_value
subixs = [[0, 1, 2, 3], [4, 5], [6], [7], [8]]
subixs = np.asarray(subixs, dtype=object)
arr_ixs = sum(subixs[msk], [])  # Flatten the list of lists
# Get lengths of each selected sublist
lengths = np.array([len(lst) for lst in subixs[msk]])
# Repeat values accordingly
new_arr_value = np.repeat(new_value, lengths)
# Assign values
arr[arr_ixs] = new_arr_value

Explanation:

  • lengths gives how many times each value should be repeated based on the size of the sublist.

  • np.repeat vectorizes the expansion of new_value to the desired length.

  • This avoids any explicit Python loops for expansion.

🌐
W3Schools
w3schools.com › python › numpy › numpy_array_join.asp
NumPy Joining Array
import numpy as np arr1 = np.array([[1, ... stacking is done along a new axis. We can concatenate two 1-D arrays along the second axis which would result in putting them one over the other, ie....
🌐
Plotly
community.plotly.com › 📊 plotly python
How to overlay two images with opacity - 📊 Plotly Python - Plotly Community Forum
June 7, 2023 - I have a simple problem, I want to overlay two rgb images (np.arrays with three channels and same size) over each other, with opacity setting for the top so I can see both. fig_visual_check = go.Figure() fig_visual_check = fig_visual_check.add_trace(go.Image(z=images_merged_visual[0], opacity=0.5)) fig_visual_check = fig_visual_check.add_trace(go.Image(z=images_merged_visual[1], opacity=1)) fig_visual_check However, the result is just a black image.
🌐
GitConnected
levelup.gitconnected.com › how-to-approach-image-overlay-problems-ad2d4a8e22bc
How to approach image overlay problems | by Shaurya Agarwal | Level Up Coding
December 14, 2021 - numpy offers a function numpy.dstack() to stack values against along the depth. First, we need a dummy array of the same size as of the image.
🌐
SciPy
docs.scipy.org › doc › numpy-1.10.4 › reference › routines.ma.html
Masked array operations — NumPy v1.10 Manual
May 29, 2016 - NumPy Reference · Routines · index · next · previous · Masked array operations · Constants · Creation · From existing data · Ones and zeros · Inspecting the array · Manipulating a MaskedArray · Changing the shape · Modifying axes · Changing the number of dimensions ·
🌐
Pythonfixing
pythonfixing.com › 2022 › 03 › fixed-overlay-image-segmentation-with.html
Redirecting...
March 3, 2022 - We cannot provide a description for this page right now