Python code to compare images in python

I am working on a project in which at some point I need to compare two images. Tell someone please help me with this way. How images are screenshots of software. I wanted to check if the two images are identical, including the numbers and letters displayed on the image (software screenshot).

+6
source share
3 answers

There are the following methods for correct comparison.

  • Firstly, this is the root mean square difference #

To get an idea of โ€‹โ€‹how similar the two images are, you can calculate the RMS value of the difference between the images. If the images are exactly identical, this value is zero. The following function uses the difference function, and then calculates the RMS value from the histogram of the resulting image.

# Example: File: imagediff.py import ImageChops import math, operator def rmsdiff(im1, im2): "Calculate the root-mean-square difference between two images" h = ImageChops.difference(im1, im2).histogram() # calculate rms return math.sqrt(reduce(operator.add, map(lambda h, i: h*(i**2), h, range(256)) ) / (float(im1.size[0]) * im1.size[1])) 
  • Another is an accurate comparison

The fastest way to determine if two images have exactly the same content is to get the difference between the two images, and then calculate the bounding rectangle of non-zero areas in that image. If the images are identical, all the pixels in the difference image are zero, and the bounding box function returns None.

 import ImageChops def equal(im1, im2): return ImageChops.difference(im1, im2).getbbox() is None 
+6
source

I support a Python library called pyssim that uses the Structured Similarity Method (SSIM) to compare two images.

It has no python bindings, but the perceptualdiff program is also amazing when comparing two images - and pretty fast.

+6
source

I cannot give a ready answer, but I will point you (I think) in the right direction. An easy way to compare two images is to create a hash of their binary representations, and then see if these hashes are the same. One problem is to use the hash function that you want to use, and you should look for one that has a low chance of a collision, and the other is that the image file probably contains metadata attached to the original binary information, so you will have to look for how to cut off this metadata to compare images using only their binary information. Also, I donโ€™t know for sure, but probably the binary representation of the image encoded in jpg is different from the image encoded in png, so you should be aware of this.

+1
source

Source: https://habr.com/ru/post/922154/


All Articles