Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add two 3D numpy arrays with a 2D mask

I would like to add two 3D numpy arrays (RGB image arrays) with a 2D mask generated by some algorithms on a greyscale image. What is the best way to do this?

As an example of what I am trying to do:

from PIL import Image, ImageChops, ImageOps
import numpy as np

img1=Image.open('./foo.jpg')
img2=Image.open('./bar.jpg')

img1Grey=ImageOps.grayscale(img1)
img2Grey=ImageOps.grayscale(img2)

# Some processing for example:
diff=ImageChops.difference(img1Grey,img2Grey)
mask=np.ma.masked_array(img1,diff>1)

img1Array=np.asarray(im1)
img2Array=np.asarray(im2)

imgResult=img1Array+img2Array[mask]

I was thinking:
1) break up the RGB image and do each color separately
2) duplicate the mask into a 3D array

or is there a more pythonic way to do this?

Thanks in advance!

like image 578
Onlyjus Avatar asked Dec 06 '25 14:12

Onlyjus


1 Answers

Wish I could add a comment instead of an answer. Anyhow:

masked_array is not for making masks. It's for including only the data outside the mask in calculations such as sum, mean, etc.. scientific statistical applications. It's comprised of an array and the mask for the array. It's probably NOT what you want.

You probably just want a normal boolean mask, as in:

mask = diff>1

Then you'll need to modify the shape so numpy broadcasts in the correct dimension, then broadcast it into the 3rd dimension:

mask.shape = mask.shape + (1,)
mask = np.broadcast_arrays(img1Array, mask)[1]

After that, you can just add the pixels:

img1Array[mask] += img2Array[mask]

A further point of clarification:

imgResult=img1Array+img2Array[mask]

That could never work. You are saying 'add some of the pixels from img2Array to all of the pixels in img1Array' 6_9

If you want to apply a ufunc between two or more arrays, they must be either the same shape, or broadcastable to the same shape.

like image 132
kampu Avatar answered Dec 08 '25 03:12

kampu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!