Search code examples
pythonnumpyopen-sourcegdal

Replace regions in a raster image with values from another image in python


I have two raster images of the same area and x,y dimensions as numpy arrays. Image 1 is a land-use classification (e.g. with classes 0 to 5) and image 2 is a cloud-shadow mask (with the values: 0 = cloudfree, 255 = cloud/ shadow areas).
I want to combine those images. Either take/clip all the 255 values from image 2 and mosaic them onto image 1. OR replace all the 0 values in image 2 with the values found at the specific pixel position in image 1.

I tried to make the 2d arrays 1d and replace the 0 values but then couldn't convert it correctly back into 2d.

What would be the easiest or best way to do this raster calculation completely open-source in python???


Solution

  • You can do this with numpy's boolean indexing feature.

    img1 = np.array([[0, 1, 0, 1],[1, 0, 1, 0]])
    img2 = np.array([[1, 2, 3, 4],[5, 6, 7, 8]])
    bool_arr = img1 == 0
    img1[bool_arr] = img2[bool_arr]
    print(img1)
    # outputs: [[1 1 3 1]
    #           [1 6 1 8]]