코사인 유사도를 이용해 두 이미지가 얼마나 유사한지 알 수 있다. (참고한 블로그)
이전 포스트 중에 두 벡터의 내적(Dot product)을 설명하는 포스트에서 잠깐 코사인 유사도를 언급한 적이 있다.
이를 이용해 두 이미지의 유사도를 대략적으로 측정해볼 수 있다.
코드를 각 단계별로 설명하자면 다음과 같다.
10 x 10
으로 resizing 한다.10 x 10 x 3
의 3 차원 이미지를 (300, )
의 vector로 변환한다.python 3.8.16
Pillow 10.1.0
numpy 1.24.4
import os
import numpy as np
from PIL import Image
def mini_img(img_path, resize_shape = (10, 10)):
img = Image.open(img_path)
img = img.resize(resize_shape)
return img
def cosine_similarity(img1, img2):
array1 = np.array(img1)
array2 = np.array(img2)
assert array1.shape == array2.shape
h, w, c = array1.shape
len_vec = h * w * c
vector_1 = array1.reshape(len_vec,) / 255.
vector_2 = array2.reshape(len_vec,) / 255.
cosine_similarity = np.dot(vector_1, vector_2) / (np.linalg.norm(vector_1) * np.linalg.norm(vector_2))
return cosine_similarity
img1_path = "./test_img1.jpg"
img2_path = "./test_img2.jpg"
img1 = mini_img(img1_path)
img2 = mini_img(img2_path)
score = cosine_similarity(img1, img2)