0

I want to compare to images in python, say imageA.jpg and imageB.jpg. I do it this way:

f = open('./imageA.jpg','rb')
imgA = f.read()
f.close()
f = open('./imageB.jpg','rb')
imgB = f.read()
f.close()
imagesEqual = imgA == imgB

The last line basically checks for string equality of the binary data read from the two image files. Now, a lot of stackoverflow questions and google searches suggest to use python modules like ImageChops or OpenCV. Is the way I am doing this incorrect? If so why?

Thanks!

eknight7
  • 11
  • 3
  • If you want exact file equality, that's fine. If you want to allow some differences (say, 1 pixel in `imageA` is a bit lighter than the same pixel in `imageB`), then of course it's useless ;-) – Tim Peters Oct 12 '13 at 03:50
  • Even if both images are exactely the same down to the last pixel, they won't be equal if for instance some header (jfif, exif) is different. You are not comparing graphics, you are comparing bytes. – Hyperboreus Oct 12 '13 at 08:39
  • So can 2 images have the same exif/jiff header data? How can I compare bytes that are only the image data and not the header data of the file? – eknight7 Oct 12 '13 at 15:33

2 Answers2

0

If all that you want to know is whether they are different, than try:

import filecmp
if filecmp.cmp(filename1, filename2, shallow=False):

from In Python, is there a concise way of comparing whether the contents of two text files are the same?

Community
  • 1
  • 1
Blue Ice
  • 7,294
  • 5
  • 30
  • 48
  • So different here means images are different or files are different? I wanted to check if the images are different. Does this avoid comparing header data (exif or jiff) mentioned by Hyperboreus above? – eknight7 Oct 12 '13 at 15:32
0

With your code you compare the files, not the images. If you want to compare the real content of the images (i.e. the pixels values), you should open and load the two images (imgA=Image.open('./imageA.jpg'), imgA.load()) and compare them, because sometimes the files of two identical images can include different headers, metadata… in such cases the images are identical but the files are different.

Raluca
  • 281
  • 2
  • 8