请编写一个Python程序,使用yolo进行人脸识别
时间: 2024-05-07 16:16:33 浏览: 137
好的,以下是使用yolo进行人脸识别的Python程序:
```python
import cv2
import numpy as np
# 加载yolo模型
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
# 加载类别标签
classes = []
with open("coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
# 设置输出层的名称
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 读取图片并进行预处理
img = cv2.imread("test.jpg")
height, width, channels = img.shape
blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
# 将预处理后的图片输入到yolo模型中进行推理
net.setInput(blob)
outs = net.forward(output_layers)
# 解析推理结果
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5 and class_id == 0:
# 保存人脸的类别id、置信度和位置信息
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
# 进行非极大值抑制
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 在图片上绘制检测结果
font = cv2.FONT_HERSHEY_PLAIN
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]]) + " " + str(round(confidences[i], 2))
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(img, label, (x, y - 5), font, 1, (0, 255, 0), 1)
# 显示绘制后的图片
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这是一个使用yolo进行人脸识别的简单Python程序,使用时需要先下载yolo的模型文件(yolov3.weights和yolov3.cfg),以及类别标签文件(coco.names)。程序读取图片后,将其进行预处理并输入到yolo模型中进行推理,解析推理结果并进行非极大值抑制,最后在图片上绘制检测结果并显示出来。
阅读全文