这六个变量的含义如下:
-
image_path :输入图像的路径。
-
detector_path:OpenCV 深度学习人脸检测器的路径。 使用这个模型来检测人脸 ROI 在图像中的位置。
-
embedding_path : OpenCV 深度学习人脸编码模型的路径。 我们将使用这个模型从人脸 ROI 中提取 128 维人脸嵌入——然后将把数据输入到识别器中。
-
recognizer_path :识别器模型的路径。
-
label_path : 标签编码器的路径。
-
confidence_low:过滤弱人脸检测的可选阈值。
接下来是代码的主体部分:
加载序列化人脸检测器
print(“[INFO] loading face detector…”)
protoPath = os.path.sep.join([detector_path, “deploy.proto.txt”])
modelPath = os.path.sep.join([detector_path,“res10_300x300_ssd_iter_140000_fp16.caffemodel”])
detector = cv2.dnn.readNetFromCaffe(protoPath, modelPath)
加载我们序列化的人脸编码模型
print(“[INFO] loading face recognizer…”)
embedder = cv2.dnn.readNetFromTorch(embedding_path)
加载实际的人脸识别模型和标签编码器
recognizer = pickle.loads(open(recognizer_path, “rb”).read())
le = pickle.loads(open(label_path, “rb”).read())
加载图像,将其调整为宽度为 600 像素(同时保持纵横比),然后抓取图像尺寸
image = cv2.imread(image_path)
image = resize(image, width=600)
(h, w) = image.shape[:2]
从图像构建一个 blob
imageBlob = cv2.dnn.blobFromImage(
cv2.resize(image, (300, 300)), 1.0, (300, 300),
(104.0, 177.0, 123.0), swapRB=False, crop=False)
应用 OpenCV 的基于深度学习的人脸检测器来定位输入图像中的人脸
detector.setInput(imageBlob)
detections = detector.forward()
loop over the detections
for i in range(0, detections.shape[2]):
提取与预测相关的置信度(即概率)
confidence = detections[0, 0, i, 2]
filter out weak detections
if confidence > confidence_low:
计算人脸边界框的 (x, y) 坐标
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype(“int”)
提取人脸ROI
face = image[startY:endY, startX:endX]
(fH, fW) = face.shape[:2]
确保人脸宽度和高度足够大
if fW < 20 or fH < 20:
continue
为人脸 ROI 构造一个 blob,然后将 blob 通过我们的人脸嵌入模型来获得人脸的 128-d 量化
faceBlob = cv2.dnn.blobFromImage(face, 1.0 / 255, (96, 96),
(0, 0, 0), swapRB=True, crop=False)
embedder.setInput(faceBlob)
vec = embedder.forward()
执行分类以识别人脸
preds = recognizer.predict_proba(vec)[0]
j = np.argmax(preds)
proba = preds[j]
name = le.classes_[j]
绘制人脸的边界框以及相关的概率
text = “{}: {:.2f}%”.format(name, proba * 100)
y = startY - 10 if startY - 10 > 10 else startY + 10
cv2.rectangle(image, (startX, startY), (endX, endY),
(0, 0, 255), 2)
cv2.putText(image, text, (startX, y),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0,