Pillow和Numpy的图像演绎 [英] Image deduction with Pillow and Numpy
问题描述
我有两张图片:
和
我想导出一个只有红色Hello的图像:
所以我正在运行一个简单的演绎python脚本:
来自PIL导入图片
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)
但是这会返回:
我的代码返回:
对为什么它如此像素化而感到困惑!
将第二张图片中不需要的像素设置为0可能更容易吗?
im = im2.copy()
im [im1 == im2] = 0
im = Image.fromarray(im)
似乎对我有用(显然只是因为我使用过你的更大的文物) r上传JPG)
也可以这样做没有numpy:
来自PIL导入ImageChops
来自PIL import Image
root ='/ root /'
im1 = Image.open(root +'1.jpg')
im2 = Image.open(root +'2.jpg')
def非零(a):
如果< b,则返回0 10 else 255
mask = Image.eval(ImageChops.difference(im1,im2),nonzero).convert('1')
im = Image.composite(im2 ,Image.eval(im2,lambda x:0),mask)
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!
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)
这篇关于Pillow和Numpy的图像演绎的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!