Highlight image with pillow and knife.

I have two images: enter image description here

and

enter image description here

I want to export the image with red "Hello", as:

enter image description here

So, I run simple python script output:

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

not higher. What am I doing wrong? Also do I need numpy or can I only do this with the library Pillow?


Edit:

It should also work with such images:

enter image description here

which returns my code:

enter image description here

It is vague why it is so pixelated around the edges!

+4
source share
1 answer

Perhaps it's easier to just 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, only with large artifacts, because I used your loaded JPGs)

Script result

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)
+3

Source: https://habr.com/ru/post/1689196/


All Articles