Image Processing/Cv2

OpenCV를 이용해서 두 개의 이미지 비교하기 (SSIM)

jinmc 2021. 3. 10. 11:17
반응형

레퍼런스 : ourcodeworld.com/articles/read/991/how-to-calculate-the-structural-similarity-index-ssim-between-two-images-with-python

 

opencv를 이용해서 두 개의 이미지를 비교하는 방법에 대해서 알아보겠습니다.

 

# Usage:
#
# python3 script.py -f original.png -s modified.png
# Based on: https://github.com/mostafaGwely/Structural-Similarity-Index-SSIM-

# 1. Import the necessary packages
#from skimage.measure import compare_ssim as ssim # deprecated (old version)
from skimage.metrics import structural_similarity as ssim 
import argparse
import imutils
import cv2
from skimage import io

# 2. Construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-f", "--first", required=True, help="Directory of the image that will be compared")
ap.add_argument("-s", "--second", required=True, help="Directory of the image that will be used to compare")
args = vars(ap.parse_args())

# 3. Load the two input images
imageA = cv2.imread(args["first"])
imageB = cv2.imread(args["second"])
# 만약 url에서 불러올 거면 다음을 활용
#imageA = io.imread(args["first"])
#imageB = io.imread(args["second"])


# 4. Convert the images to grayscale
grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)

# 5. Compute the Structural Similarity Index (SSIM) between the two
#    images, ensuring that the difference image is returned
(score, diff) = ssim(grayA, grayB, full=True)
diff = (diff * 255).astype("uint8")

# diff가 어떻게 되는지 볼 수 있습니다.
#cv2.imshow('diff',diff)
#cv2.waitKey(0)

# 6. You can print only the score if you want
print("SSIM: {}".format(score))

가장 핵심적인 함수는 skimage.metrics 의 structural images입니다.

scikit-image.org/docs/dev/api/skimage.metrics.html#skimage.metrics.structural_similarity

더 자세한 내용은.. 링크를 참고하는 게 좋은듯 합니다. (어려움...)

 

코드에 코멘트로 설명을 많이 달아놓았는데, 결국 핵심은 흑백사진으로 변환 (4번) 이후 

ssim함수를 불러서 그 유사성을 볼 수 있습니다. (score로)

score는 -1부터 1까지의 값이며, 1이면 완벽하게 똑같은 이미지로 볼 수 있습니다.

diff를 이용해서 어떻게 되는지도 볼 수 있습니다.

반응형