Compare Images in Python

前端 未结 3 1126
[愿得一人]
[愿得一人] 2020-12-28 10:21

I need to compare two images that are screenshots of a software. I want to check if the two images are identical, including the numbers and letters displayed in the images.

3条回答
  •  温柔的废话
    2020-12-28 11:19

    There are following ways to do the proper comparison.

    • First is the Root-Mean-Square Difference #

    To get a measure of how similar two images are, you can calculate the root-mean-square (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 Exact Comparison #

    The quickest way to determine if two images have exactly the same contents is to get the difference between the two images, and then calculate the bounding box of the non-zero regions in this image. If the images are identical, all 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
    

提交回复
热议问题