Image deduction with Pillow and Numpy

Viewed 937

I have two images: enter image description here

and

enter image description here

I want to export an image that just has the red "Hello" like:

enter image description here

So I am running a simple deduction python script:

from PIL import Image
import numpy as np

root = '/root/'
im1 = np.asarray(Image.open(root+'1.jpg'))
im2 = np.asarray(Image.open(root+'2.jpg'))

deducted_image = np.subtract(im1, im2)

im = Image.fromarray(np.uint8(deducted_image))
im.save(root+"deduction.jpg")

But this returns:

enter image description here

rather than the above. What am I doing wrong? Also do I need numpy or can I do this with just the Pillow Library?


Edit:

It should also work with images like this:

enter image description here

which my code returns:

enter image description here

Confused as to why it is so pixelated around the edges!

1 Answers

It is perhaps easier just to set the pixels you don't want in the second image to 0?

im = im2.copy()
im[im1 == im2] = 0
im = Image.fromarray(im)

seems to work for me (obviously just with bigger artifacts because I used your uploaded JPGs)

Result of script

It is also possible to do this without numpy:

from PIL import ImageChops
from PIL import Image

root = '/root/'
im1 = Image.open(root + '1.jpg')
im2 = Image.open(root + '2.jpg')

def nonzero(a):
    return 0 if a < 10 else 255

mask = Image.eval(ImageChops.difference(im1, im2), nonzero).convert('1')

im = Image.composite(im2, Image.eval(im2, lambda x: 0), mask)
Related