Célok
Csomagok beillesztése. Az SSIM mérték implementációja a Scikit-image csomagban található. Az MSE mértéket magunk definiáljuk függvényként.
# mse function from:
# http://www.pyimagesearch.com/2014/09/15/python-compare-two-images/
# import the necessary packages
from skimage.metrics import structural_similarity as ssim
import numpy as np
import cv2
Képpontok közötti különbség számítása. A két képet float típusúként kezeljük. Összegezzük az intenzitásonkénti különbségek négyzetét, majd az összeget osztjuk a képpárok számával.
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
Szöveg kiírás a képre segédfüggvény.
def put_text(img, text, pos1, pos2):
cv2.putText(img, text, pos2, cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 0))
cv2.putText(img, text, pos1, cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255))
Képek közötti hasonlóság számítása és megjelenítése. Az fname paraméter átadásakor az adott nevű fájlba íródik az egymásra vetített képi eredmény.
def show_similarity(caption, img1, img2, fname=None):
m = mse(img1, img2)
s = ssim(img1, img2)
mse_text = 'MSE: {:.2f}'.format(m)
ssim_text = 'SSIM: {:.2f}'.format(s)
print(caption)
print(mse_text)
print(ssim_text)
image_reg_blend = cv2.merge((np.zeros((h, w), np.uint8), img1, img2))
put_text(image_reg_blend, caption, (1, 15), (2, 16))
put_text(image_reg_blend, ssim_text, (1, h-15), (2, h-14))
put_text(image_reg_blend, mse_text, (1, h-2), (2, h-1))
cv2.imshow('Registered (blended)', image_reg_blend)
if fname:
cv2.imwrite(fname, image_reg_blend)
cv2.waitKey(0)
Főprogram. Képek beolvasása, szélesség és magasság egyezés ellenőrzése.
# Read the images
original = cv2.imread("sim/mr01.png", cv2.IMREAD_GRAYSCALE)
transformed = cv2.imread("sim/mr01_rot.png", cv2.IMREAD_GRAYSCALE)
h, w = original.shape[:2]
h2, w2 = transformed.shape[:2]
assert h == h2 and w == w2 and h > 0 and w > 0
Háromféle képi összehasonlítás hívása
show_similarity('Original - Original', original, original)
show_similarity('Original - Transformed', original, transformed)
show_similarity('Transformed - Transformed', transformed, transformed)