-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest.py
53 lines (40 loc) · 1.49 KB
/
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from keras_vggface.utils import preprocess_input
from keras_vggface.vggface import VGGFace
import numpy as np
import pickle
from sklearn.metrics.pairwise import cosine_similarity
import cv2
from mtcnn import MTCNN
from PIL import Image
feature_list = np.array(pickle.load(open('embedding.pkl', 'rb')))
filenames = pickle.load(open('filenames.pkl', 'rb'))
model = VGGFace(model='resnet50', include_top=False,
input_shape=(224, 224, 3), pooling='avg')
detector = MTCNN()
# load img -> face detection
sample_img = cv2.imread('sample\download.jpeg')
results = detector.detect_faces(sample_img)
x, y, width, height = results[0]['box']
face = sample_img[y:y+height, x:x+width]
#cv2.imshow('output', face)
# cv2.waitKey(0)
# extract its features
image = Image.fromarray(face)
image = image.resize((224, 224))
face_array = np.asarray(image)
face_array = face_array.astype('float32')
expanded_img = np.expand_dims(face_array, axis=0)
preprocessed_img = preprocess_input(expanded_img)
result = model.predict(preprocessed_img).flatten()
# print(result)
# print(result.shape)
similarity = []
for i in range(len(feature_list)):
similarity.append(cosine_similarity(result.reshape(
1, -1), feature_list[i].reshape(1, -1))[0][0])
index_pos = sorted(list(enumerate(similarity)),
reverse=True, key=lambda x: x[1])[0][0]
temp_img = cv2.imread(filenames[index_pos])
cv2.imshow('output', temp_img)
cv2.waitKey(0)
# recommend that image