NumPy, PIL adding an image

I'm trying to add two images together using NumPy and PIL. The way I would do this in MATLAB would be something like:

>> M1 = imread('_1.jpg');
>> M2 = imread('_2.jpg');
>> resM = M1 + M2;
>> imwrite(resM, 'res.jpg');

I get something like this:

alt text

Using a compositing program and adding the images the MATLAB result seems to be right.

In Python I'm trying to do the same thing like this:

from PIL import Image
from numpy import *

im1 ='/Users/rem7/Desktop/_1.jpg')
im2 ='/Users/rem7/Desktop/_2.jpg')

im1arr = asarray(im1)
im2arr = asarray(im2)

addition = im1arr + im2arr

resultImage = Image.fromarray(addition)'/Users/rem7/Desktop/a.jpg')

and I get something like this:

alt text

Why am I getting all those funky colors? I also tried using ImageMath.eval("a+b", a=im1, b=im2), but I get an error about RGB unsupported.

I also saw that there is an Image.blend() but that requires an alpha.

What's the best way to achieve what I'm looking for?

Source Images (images have been removed):

alt text alt text

Humm, OK, well I added the source images using the add image icon and they show up when I'm editing the post, but for some reason the images don't show up in the post.

(images have been removed) 2013 05 09

Asked by: Blake470 | Posted: 06-12-2021

Answer 1

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:


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)/2
addition = 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.

Answered by: Maya235 | Posted: 07-01-2022

Answer 2

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 Image
im1 ='/Users/rem7/Desktop/_1.jpg')
im2 ='/Users/rem7/Desktop/_2.jpg')

Answered by: Lucas336 | Posted: 07-01-2022

Answer 3

To clamp numpy array values:

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

Answered by: First Name759 | Posted: 07-01-2022

Answer 4

It seems the code you posted just sums up the values and values bigger than 256 are overflowing. You want something like "(a + b) / 2" or "min(a + b, 256)". The latter seems to be the way that your Matlab example does it.

Answered by: Anna794 | Posted: 07-01-2022

Answer 5

Your sample images are not showing up form me so I am going to do a bit of guessing.

I can't remember exactly how the numpy to pil conversion works but there are two likely cases. I am 95% sure it is 1 but am giving 2 just in case I am wrong. 1) 1 im1Arr is a MxN array of integers (ARGB) and when you add im1arr and im2arr together you are overflowing from one channel into the next if the components b1+b2>255. I am guessing matlab represents their images as MxNx3 arrays so each color channel is separate. You can solve this by splitting the PIL image channels and then making numpy arrays

2) 1 im1Arr is a MxNx3 array of bytes and when you add im1arr and im2arr together you are wrapping the component around.

You are also going to have to rescale the range back to between 0-255 before displaying. Your choices are divide by 2, scale by 255/array.max() or do a clip. I don't know what matlab does

Answered by: Kellan219 | Posted: 07-01-2022

Similar questions

python - Adding numpy array to a heap queue

Can someone please explain why the following code results in a ValueError? import heapq import numpy as np a = np.ones((2, 2), dtype=int) states = [] heapq.heappush(states, (0, a)) heapq.heappush(states, (0, a.copy())) The error message is: Traceback (most recent call last): File "", line 8, in <module> heapq.heappush(states, (0, a.copy())) ValueError: The...

python - Adding to a view of a numpy array

This question already has answers here:

python - Adding a bias to numpy array

I have two numpy arrays, one is 2D of dimension (a, b) and the other is 1D of dimension a. I want to add the single value for each index of the 1D array to each member of the same index in the 2D array. Here's an example of what I'm trying to do: import numpy as np firstArr = np.random.random((5,6)) secondArr = np.linspace(0, 4, 5) I know I can do what I want with the loop: fo...

python - Adding 2 value using numpy

I am trying to write a an input code that can put 2 output all together and add it up. The code is below; import numpy as np x, y = input("Insert value").split() print(x) print(y) print(np.add(x,y)) Output: 4 3 --------------------------------------------------------------------------- UFuncTypeError Traceback (most recent call last) &lt...

python - Adding Cookie to ZSI Posts

I've added cookie support to SOAPpy by overriding HTTPTransport. I need functionality beyond that of SOAPpy, so I was planning on moving to ZSI, but I can't figure out how to put the Cookies on the ZSI posts made to the service. Without these cookies, the server will think it is an unauthorized request and it will fail. How can I add cookies from a Python CookieJar to ZSI requests?

python - Adding REST to Django

linux - python or bash - adding " at beginning of line and ", at end of line

I have text file with something like first line line nr 2 line three etc And i want to generate "first line", "line nr 2", "line three", I wonder how to do this in python or maybe in bash if it's easier/quicker. I know there is different code for opening file and different for reading only one line in python(?) but i'm not sure which option to use ...

python - Why do I need to save this model before adding it to another one?

In django, I'm trying to do something like this: # if form is valid ... article = = req.user product_name = form.cleaned_data['product_name'] try: article.product = Component.objects.get(name=product_name) except: article.product = Component(name=product_name) # do some more form processing ... But then it tells me:

Python GTK adding signal to a combo box

I create a combo box using PyGTK: fileAttrCombo = gtk.ComboBox(); I want to attach a signal handler for this combo box. This signal handler handles when user change selection in the combo box. What is be the best approach to do this ?

python - Adding string to end of URL

To practise some more bits of python I've been having a go at the challenges on In brief, this challenge as a first step requires one to load an html page from a url with a number at the end. The page contains a single line of text which has in it a number. That number is used to replace the existing one in the url, and so take you to the next page in the sequence. Apparently this continues for ...

python - adding a header to pyqt list

i want to add a headers and index to a list in pyqt , it's really not important what list of QT (qlistwidget , qlistview , qtablewidget, qtreeview) in short .. i want something like the spin box delegate example in the pyqt demo ... but instead of the index in the column headers i want a strings ... hope the idea is clear enough thanx in advance

python - Adding custom fields to users in Django

I am using the create_user() function that Django provides to create my users. I want to store additional information about the users. I tried following the instructions given at

python - Error when adding value to array

with open('file00.txt') as f00: for line in f00: farr=array.append(float(line)) print "farr= ",farr i get: farr=array.append(float(line)) AttributeError: 'module' object has no attribute 'append' does anyone know why I get this? do I have to import something? am I doing it completely wrong? thanks

python - Adding opion to form label

I have form declared like this: field = forms.MultipleChoiceField(choices = STATES, widget=forms.CheckboxSelectMultiple, label_suffix= "(%d)" % id) let say STATES is decladed as STATES = [(0, 'foo'), (1, 'bar')] And I want to acheve labels that looks like this: foo (0) bar (1) id should be option value (I'll call func there, so it has to b...

python - What's the best Django search app?

How can I use a DLL file from Python?

What is the easiest way to use a DLL file from within Python? Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.

python - PubSub lib for c#

Is there a c# library which provides similar functionality to the Python PubSub library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.

python - What is the best way to copy a list?

This question already has answers here:

python - Possible Google Riddle?

My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that eac...

How do you check whether a python method is bound or not?

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?

ssh - How to scp in Python?

What's the most pythonic way to scp a file in Python? The only route I'm aware of is os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted'...

python - How do I create a new signal in pygtk

I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.

python - What do I need to import to gain access to my models?

I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?

python - How do I edit and delete data in Django?

I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete! Please show me an example of the code ...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python