NumPy, PIL adding an image NumPy, PIL adding an image numpy numpy

NumPy, PIL adding an image


As everyone suggested already, the weird colors you're observing are overflow. And as you point out in the comment of schnaader's answer you still get overflow if you add your images like this:

addition=(im1arr+im2arr)/2

The reason for this overflow is that your NumPy arrays (im1arr im2arr) are of the uint8 type (i.e. 8-bit). This means each element of the array can only hold values up to 255, so when your sum exceeds 255, it loops back around 0:

>>>array([255,10,100],dtype='uint8') +  array([1,10,160],dtype='uint8')array([ 0, 20,  4], dtype=uint8)

To avoid overflow, your arrays should be able to contain values beyond 255. You need to convert them to floats for instance, perform the blending operation and convert the result back to uint8:

im1arrF = im1arr.astype('float')im2arrF = im2arr.astype('float')additionF = (im1arrF+im2arrF)/2addition = additionF.astype('uint8')

You should not do this:

addition = im1arr/2 + im2arr/2

as you lose information, by squashing the dynamic of the image (you effectively make the images 7-bit) before you perform the blending information.

MATLAB note: the reason you don't see this problem in MATLAB, is probably because MATLAB takes care of the overflow implicitly in one of its functions.


Using PIL's blend() with an alpha value of 0.5 would be equivalent to (im1arr + im2arr)/2. Blend does not require that the images have alpha layers.

Try this:

from PIL import Imageim1 = Image.open('/Users/rem7/Desktop/_1.jpg')im2 = Image.open('/Users/rem7/Desktop/_2.jpg')Image.blend(im1,im2,0.5).save('/Users/rem7/Desktop/a.jpg')


To clamp numpy array values:

>>> c = a + b>>> c[c > 256] = 256