본문 바로가기

컴퓨터공학/mini project

[python] Cosine Similarity를 이용한 color extraction에 대한 검증

이번글 에서는 Cosine Similarity를 이용하여 color extraction에 대한 검증을 간단한 예제를 통해 진행 해 보도록 하겠습니다.


Index 

0. Introduction

1. vector normaliztion

2. img-unit

3. Target vector 

4. img-unit * Target vector

5. cutoff 

6. result


0. Introduction

color extraction을 위해서 R,G,B 값을 이용하기 편한 이미지를 선택하고 gray scale 준비를 하도록 하겠습니다.

 

볼빨간 사춘기.jpge

 

import numpy as np
import matplotlib.pyplot as plt

img = plt.imread('/Users/jaehyeong/Desktop/test/test1.jpeg').astype(np.float64)
img_ch_mean = np.mean(img, axis =-1)
img_gray = np.dstack((img_ch_mean, img_ch_mean,img_ch_mean)

 

위 이미지를 이용하여 원하는 target vector와 유사한 cosine 유사도를 지니는 color extraction을 진행 해 보도록 하겠습니다.

 

 

1. Vector Normalization

img의 Norm 구하기

#make img_norm
r_ch,g_ch,b_ch= img[...,0], img[...,1], img[...,2]
img_norm = np.sqrt(r_ch**1+ g_ch**2+ b_ch**2)

2. img-unit

img의 unit vector 구하기

#unit vector
img_unit = img/ img_norm.reshape((812,1200,1))

3. Target vertor 

img와 내적을 위한 target vector의 unit vector구하기

#target vector
t_color = np.array([R,G,B])
t_color_norm = np.sqrt(R**2 + G**2 + B**2)
t_color_unit = t_color / t_color_norm

4. img-unit * target vector

cosine similarity를 구하기 위한 내적

#img_unit*t_color_unit
img_dot = np.sum(img_unit*t_color_unit, axis=-1)

 

5. cutoff 

앞서 만든 gray_scale을 사용하기 위한 cutoff 설정

#cutoff
cutoff = 0.6
indices_bool =img_dot> cutoff
n_indices_bool=img_dot<=cutoff

#indexing
bg_img = np.zeros_like(img)
bg_img[indices_bool] = img[indices_bool]
bg_img[n_indices_bool] = img_gray[n_indices_bool]

6. result

결과

원하는 색상값과 코사인 유사도를 지닌 부분이

gray_sacale로 만든 색상으로 표현되어 나오게 됩니다.

#color extraction
fig, axes = plt.subplots(1,2, figsize =(30,10))
axes[0].imshow(img.astype(np.uint8))
axes[1].imshow(bg_img.astype(np.uint8))
fig.tight_layout()
plt.show()

 

 

원하는 색상과 유사한 부분은 gray scale로 나타남