Mark K
Mark K

Reputation: 9376

Comparing two images/pictures, and mark the difference

I am learning to compare two images/pictures. I found the post Compare two images the python/linux way is very useful and I have some questions regarding the technique.

Question 1:

The post shows ways to compare 2 pictures/images. Probably the easiest way is:

from PIL import Image
from PIL import ImageChops

im1 = Image.open("file1.jpg")
im2 = Image.open("file2.jpg")

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

print diff

when I have 2 look alike pictures and run above, it give result:

(389, 415, 394, 420)

It’s the position on the picture where the difference in 2 pictures lies. So my question is, would it be possible to mark the difference on the picture (for example, draw a circle)?

Question 2:

import math, operator
from PIL import Image
def compare(file1, file2):
    image1 = Image.open(file1)
    image2 = Image.open(file2)
    h1 = Image.open("image1").histogram()
    h2 = Image.open("image2").histogram()

    rms = math.sqrt(reduce(operator.add, map(lambda a,b: (a-b)**2, h1, h2))/len(h1))

if __name__=='__main__':
    import sys
    file1 = ('c:\\a.jpg')        # added line
    file2 = ('c:\\b.jpg')        # added line

    file1, file2 = sys.argv[1:]
    print compare(file1, file2)

When I run above, it gives an error “ValueError: need more than 0 values to unpack”, and the problem lies in this line:

file1, file2 = sys.argv[1:]

How can I have it corrected? and I tried below it neither works.

    print compare('c:\\a.jpg', 'c:\\b.jpg')

Update

Added question following Matt's help.

It can draw a rectangle to mark the difference on the two images/pictures. When the two images/pictures looked general the same but there are small spots differences spread. It draws a big rectangle marking the big area include all the spots differences. Is there a way to identically mark the differences individually?

Upvotes: 3

Views: 6027

Answers (2)

eivl
eivl

Reputation: 148

Question 1: ImageDraw

image = Image.open("x.png")
draw = ImageDraw.Draw(image)
draw.ellipse((x-r, y-r, x+r, y+r))

Upvotes: 1

Matt
Matt

Reputation: 17649

Regarding your first question:

import ImageDraw
draw = ImageDraw.Draw(im2)
draw.rectangle(diff)
im2.show()

Regarding your second question:

The error states, that sys.argv does not contain enough values to be assigned to file1 and file2. You need to pass the names of the two files you want to compare to you python script (the variable sys.arv contains the name of your script and all the command line parameters):

python name_of_your_script.py file1.jpg file2.jpg

Upvotes: 2

Related Questions