问题
I have two images:
and
I want to export an image that just has the red "Hello" like:
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:
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:
which my code returns:
Confused as to why it is so pixelated around the edges!
回答1:
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)
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)
来源:https://stackoverflow.com/questions/47265000/image-deduction-with-pillow-and-numpy