我回来了,这就是我想出的。这有点令人困惑,因为似乎没有太大区别。我用了两张特朗普和奥巴马的照片。计算余弦相似度没有任何意义。也许我做错了什么?
import PIL
from PIL import Image
import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras.models import load_model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.image import img_to_array
from sklearn.metrics.pairwise import cosine_similarity
#load model and compile
facenet = load_model('facenet_keras.h5', compile='False')
facenet.compile(optimizer='adam', loss='categorical_crossentropy',metrics=['accuracy'])
def dist(a,b):
#prepare image for FaceNet
a,b = Image.open(a), Image.open(b)
a,b = np.array(a), np.array(b)
a,b = Image.fromarray(a), Image.fromarray(b)
a,b = a.resize((160,160)), b.resize((160,160))
a,b = img_to_array(a), img_to_array(b)
a = a.reshape((1,a.shape[0], a.shape[1], a.shape[2]))
b = b.reshape((1,b.shape[0], b.shape[1], b.shape[2]))
#get FaceNet embedding vector
a, b = facenet.predict(a), facenet.predict(b)
#compute distance metric
print((cosine_similarity(a, b)))
dist("obamaface2.jpg", "trumpface1.jpg") #images cropped to face
obamaface2
比较的输出trumpface1
是这样的:[[0.9417696]]
while trumpface1
to trumpface2
was[[0.9754221]]