Take the 2-minute tour ×

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



# Some processing for example:



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!

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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:


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.

share|improve this answer
Thanks for the answer! No wonder why I couldn't find a answer, I was going the wrong direction. It seems to have solved my problem. I have to clean up and make sure though. –  Onlyjus Oct 1 '12 at 12:16

Your Answer


