Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two images pixel-wise with PIL (Python Imaging Library)

I need a function which compares two PIL images of the same size. Let's call them A and B. The result is supposed to be a new image of the same size. If a pixels is the same in both A and B it's supposed to be set to a fixed color (e.g. black), otherwise it's supposed to be set to the same color as B.

Is there a library for implementing this functionality without an expensive loop over all pixels?

like image 387
Maarten Avatar asked May 23 '13 17:05

Maarten


People also ask

How do I compare two pixels of pixels in Python?

You can compare two images using functions from PIL. The diff object is an image in which every pixel is the result of the subtraction of the color values of that pixel in the second image from the first image.


1 Answers

Not sure about other libraries, but you can do this with PIL, with something like...

from PIL import Image, ImageChops

point_table = ([0] + ([255] * 255))

def black_or_b(a, b):
    diff = ImageChops.difference(a, b)
    diff = diff.convert('L')
    diff = diff.point(point_table)
    new = diff.convert('RGB')
    new.paste(b, mask=diff)
    return new

a = Image.open('a.png')
b = Image.open('b.png')
c = black_or_b(a, b)
c.save('c.png')
like image 173
Aya Avatar answered Oct 29 '22 14:10

Aya