similarity.py
1.21 KB
import keras
import numpy as np
from keras.applications.vgg16 import preprocess_input, VGG16
from keras.preprocessing import image
from numpy.linalg import norm
keras.backend.set_image_data_format('channels_first')
def preprocess_image(img_path):
img = image.load_img(img_path, target_size=(224, 224))
img_data = image.img_to_array(img, data_format='channels_first')
img_data = np.expand_dims(img_data, axis=0)
img_data = preprocess_input(img_data)
return img_data
class Similarity(object):
def __init__(self, dest_file_path):
self.model = VGG16(weights='imagenet', include_top=False)
self.dest = preprocess_image(dest_file_path)
def _feature(self, image):
image_features = self.model.predict(image)
image_features = image_features.reshape(7 * 7 * 512)
return image_features
def similarity(self, before_image):
"""
capture를 통해 얻은 이미지와 목표 이미지간 유사도를 계산
:return: 현재 이미지와 목표 이미지 유사도
"""
before = self._feature(before_image)
after = self._feature(self.dest)
return np.dot(before, after) / (norm(before) * norm(after))
# image path
# image..