Skip to content Skip to sidebar Skip to footer

Comparison Between Two Images In Python

I want to compare two images using Python, but I'm not familiar with this language. I have two images of the same size. I have to create an array containing the pixel-by-pixel diff

Solution 1:

As @martineau suggests, the Python Imaging Library is a good way to go. I personally also think you can use numpy and matplotlib as an alternative. The good thing about python is that you can then use the array and do operation on the whole image instead of using for loops, that would look better and be faster.

As an example I quickly ported your code to python (not sure about what filter is doing there and what value your threshold has, but rest should be pretty much the same)

I have also some doubts (you set to 255 the value after binarizing, that meaning the final average will be somehow high, maybe using values between 1 and 0 would be easier to be interpreted after, but that's up to you).

import numpy as np
import matplotlib.pyplot as plt
import sys

defbinarize(img, threshold):

    # create an image with True or False (that can be seen as 1 or 0) and multiply by 255
    binaryimg = (img > threshold).astype(int) * 255return binaryimg

defcomparison(img1, img2):

    # convert to gray. What's the filter doing?
    gray1 = rgb2gray(img1)
    gray2 = rgb2gray(img2)

    # select a threhsold value and binarize the image
    threshold = 0.5
    gray1_bin = binarize(gray1, threshold)
    gray2_bin = binarize(gray2, threshold)

    # in python you can compute a difference image.# so diff will contain in each pixel the difference between the two images
    diff = gray1_bin - gray2_bin

    # the np.mean gives you already sum / number of pixels
    average = np.mean(diff)

    return average

defrgb2gray(col_img):

    # converts images to gray
    weights = np.array([0.3, 0.59, 0.11])
    gray = np.sum([col_img[:, :, i].astype(np.float64) * weights[i] for i inrange(3)], axis=0)

    return gray

# the "main" methodif __name__ == "__main__":

    # read the images
    img = plt.imread(sys.argv[1])
    img2 = plt.imread(sys.argv[2])

    result = comparison(img, img2)

    print("The difference between the images is {}".format(result))

Hope this helps!

Post a Comment for "Comparison Between Two Images In Python"