0

I am comparing 2 images/pictures by using PIL. Below codes work on some pictures but not all.

from PIL import Image
from PIL import ImageChops
from PIL import ImageDraw

im1 = Image.open(r'c:\a.jpg')
im2 = Image.open(r'c:\aa.jpg')

diff = ImageChops.difference(im2, im1).getbbox()

print diff

draw = ImageDraw.Draw(im2)
draw.rectangle(diff)
im2 = im2.convert('RGB')
im2.save(r'c:\aaa.jpg')

For example, it doesn’t work for these 2 pictures.

a.jpg enter image description here

aa.jpg enter image description here

the output is (16, 80, 80, 144) however it doesn't draw anything on the picture.

Questions:

  1. Why is it happening?
  2. Does the file type matter? i.e. JPG compares with JPG; PNG compares with PNG; BMP compares with BMP – which format is best for comparison?
  3. Sometimes the difference lies on far distance on the picture, so it will draw a big rectangle to include the whole area. Is there a way to only draw small rectangle to mark the differeces?

Thanks.

Mark K
  • 8,767
  • 14
  • 58
  • 118
  • 1
    does your rectangle call need a colour? – user1269942 Nov 25 '14 at 07:04
  • 1
    in the openCV package, you can grab various areas of change based upon the intensity difference. for a primer: http://opencvpython.blogspot.ca/2012/06/hi-this-article-is-tutorial-which-try.html – user1269942 Nov 25 '14 at 07:07
  • Are you sure it doesnt draw enything, maybe check by chenging color of the rectangle, `draw.rectangle(diff, outline = (0,255,0))` – Marcin Nov 25 '14 at 07:09
  • thanks, user1269942. I will read the tutorial. – Mark K Nov 25 '14 at 07:59
  • @Marcin, thanks for the tip. anybody any idea if file format such as PNG, JPG, BMP etc matters? – Mark K Nov 25 '14 at 08:00

1 Answers1

2
from PIL import Image
from PIL import ImageChops
from PIL import ImageDraw

im1 = Image.open('a.jpg')
im2 = Image.open('aa.jpg')

diff = ImageChops.difference(im2, im1).getbbox()

print diff

draw = ImageDraw.Draw(im2)
draw.rectangle(diff, outline = (0,255,0))
print  help(draw.rectangle)
im2 = im2.convert('RGB')
im2.save('aaa.jpg')

Help on method rectangle in module PIL.ImageDraw:

rectangle(self, xy, fill=None, outline=None) method of PIL.ImageDraw.ImageDraw instance

So the outline parameter is None by default that's why its creating transparent rectangle here.

enter image description here

Tanveer Alam
  • 5,185
  • 4
  • 22
  • 43
  • thanks. it solved the problem. actually they are quite the same but deemed different, is there a less 'sensitive' way to compare pictures? I mean only pictures are identically different can only deemed as different. – Mark K Nov 25 '14 at 08:04
  • If you are going for Image comparison or searching any object on Images etc i would really suggest you to go for opencv. http://stackoverflow.com/questions/4196453/simple-and-fast-method-to-compare-images-for-similarity – Tanveer Alam Nov 25 '14 at 08:49