2017-02-04 170 views
1

我没有背景图像处理。我有兴趣了解这两张图片的区别。 enter image description here如何自定义图像差异产生的输出?

enter image description here

编写下面的代码后:

from PIL import Image 
from PIL import ImageChops 

im1 = Image.open("1.png") 
im2 = Image.open("2.png") 

diff = ImageChops.difference(im2, im1) 
diff.save("diff.png") 

我得到这样的输出: -

enter image description here

我要寻找一些客户化的位置:

1)我想用不同的颜色标记输出的差异。 1.png和2.png应该有不同的颜色。

2)背景应该是白色的。

3)我想我的输出有轴和轴标签。以某种方式可能吗?

+0

好的,我在编辑这个问题。 –

回答

1

您可能无法使用高级别差异方法执行此操作,但如果您自己逐个像素地比较图像,则很容易。快速尝试:

enter image description here

代码:

from PIL import Image 
from PIL import ImageDraw 
from PIL import ImageFont 

im1 = Image.open("im1.jpeg").convert('1') # binary image for pixel evaluation 
rgb1 = Image.open("im1.jpeg").convert('RGB') # RGB image for border copy 
p1 = im1.load() 
prgb1 = rgb1.load() 

im2 = Image.open("im2.jpeg").convert('1') # binary image for pixel evaluation 
p2 = im2.load() 

width = im1.size[0] 
height = im1.size[1] 

imd = Image.new("RGB", im1.size) 
draw = ImageDraw.Draw(imd) 
dest = imd.load() 
fnt = ImageFont.truetype('/System/Library/Fonts/OpenSans-Regular.ttf', 20) 

for i in range(0, width): 
     for j in range(0, height): 

     # border region: just copy pixels from RGB image 1 
      if j < 30 or j > 538 or i < 170 or i > 650: 
      dest[i,j] = prgb1[i,j] 
     # pixel is only set in im1, make red 
      elif p1[i,j] == 255 and p2[i,j] == 0: 
      dest[i,j] = (255,0,0) 
     # pixel is only set in im2, make blue 
      elif p1[i,j] == 0 and p2[i,j] == 255: 
      dest[i,j] = (0,0,255) 
     # unchanged pixel/background: make white 
      else: 
      dest[i,j] = (255,255,255) 


draw.text((700, 50),"blue", "blue", font=fnt) 
draw.text((700, 20),"red", "red", font=fnt) 
imd.show() 
imd.save("diff.png") 

这假定图像是相同的尺寸和具有同一轴线。

+0

非常感谢。对不起,延迟的回复。这是完美的。只需要传说和底部边界。我会自己尝试。 –

+0

我无法找出不同颜色的图例选项。你能帮我在这里吗?我能够适当调整极限。 –

+0

您可以使用ImageDraw文本()方法添加文本,示例如下:http://stackoverflow.com/a/16377244/571215 –