11

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?

1 Answer 1

20

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')
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! I was almost going to write that part myself in C.
what does this do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.