I’m trying to compare two images and return a score based on how similar the second image is to the original. So, I watched several videos on how to do this, but nothing seems to return the correct answer because the closer the second image to the first one is, the lower the score gets.
My idea is to have image 1
as the original image that will be used to compare the other images with. For example, images 2-4 are just for testing. The idea is to have a final image similar to image 4
that looks very similar to image 1
then compare both to see if image 4
is somewhat similar to the original. After that get the score based on how similar 4 looks compared to 1.
Here is the code:
I’m using it from this link:
Python Compare Two Images
from skimage.metrics import structural_similarity as ssim
import matplotlib.pyplot as plt
import numpy as np
import cv2
def mse(imageA, imageB):
# the 'Mean Squared Error' between the two images is the
# sum of the squared difference between the two images;
# NOTE: the two images must have the same dimension
err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2)
err /= float(imageA.shape[0] * imageA.shape[1])
# return the MSE, the lower the error, the more "similar"
# the two images are
return err
def compare_images(imageA, imageB, title):
# compute the mean squared error and structural similarity
# index for the images
m = mse(imageA, imageB)
s = ssim(imageA, imageB)
# setup the figure
fig = plt.figure(title)
plt.suptitle("MSE: %.2f, SSIM: %.2f" % (m, s))
# show first image
ax = fig.add_subplot(1, 2, 1)
plt.imshow(imageA, cmap = plt.cm.gray)
plt.axis("off")
# show the second image
ax = fig.add_subplot(1, 2, 2)
plt.imshow(imageB, cmap = plt.cm.gray)
plt.axis("off")
# show the images
plt.show()
# load the images -- the original, the original + new,
# and the original + photoshop
original = cv2.imread("Test\i1.png")
new= cv2.imread("Test\i4.png")
# convert the images to grayscale
original = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
new= cv2.cvtColor(new, cv2.COLOR_BGR2GRAY)
# initialize the figure
images = ("Original", original), ("New", new)
# compare the images
compare_images(original, new, "Original vs. New")
The problem with this is that if I test image 1
with image 2
it returns about an 80% match. But if I test image 1
with image 4
it returns a lower match at about 70%. Even though image 1
and image 4
look very similar, it’s still not the same image. It should have returned something close to 90%.
Any idea on how can I fix this or if there is another method is a lot easier. By the way, I just started to learn OpenCV.