首先,不要将原始图像存储在 blob 列中。您应该存储原始图像的矢量表示。以下 python 代码块将找到人脸图像的矢量表示。
#!pip install deepface
from deepface.basemodels import VGGFace, Facenet
model = VGGFace.loadModel() #you can use google facenet instead of vgg
target_size = model.layers[0].input_shape
#preprocess detects facial area and aligns it
img = functions.preprocess_face(img="img.jpg", target_size=target_size)
representation = model.predict(img)[0,:]
在这里,您可以将精确的图像路径(如 img.jpg 或 3D 数组)传递给 preprocess_face 的 img 参数。这样,您就可以将向量表示形式存储在 oracle 数据库的 blob 列中。
当你有一张新的人脸图像,并想在数据库中找到它的身份时,再次找到它的表示。
#preprocess detects facial area and aligns it
target_img = functions.preprocess_face(img="target.jpg", target_size=target_size)
target_representation = model.predict(target_img )[0,:]
现在,您有了目标图像的矢量表示和数据库图像的矢量表示。您需要找到目标图像表示和数据库表示的每个实例的相似度得分。
欧几里得距离是比较向量的最简单方法。
def findEuclideanDistance(source_representation, test_representation):
euclidean_distance = source_representation - test_representation
euclidean_distance = np.sum(np.multiply(euclidean_distance, euclidean_distance))
euclidean_distance = np.sqrt(euclidean_distance)
return euclidean_distance
我们会将每个数据库实例与目标进行比较。假设数据库实例的表示存储在表示对象中。
distances = []
for i in range(0, len(representations)):
source_representation = representations[i]
#find the distance between target_representation and source_representation
distance = findEuclideanDistance(source_representation, target_representation )
distances.append(distance)
距离列表存储数据库中每个项目到目标的距离。我们需要找到最短距离。
import numpy as np
idx = np.argmax(distances)
idx是目标图片在数据库中的id。