yolo检测人脸代码
时间: 2023-10-06 11:13:43 浏览: 44
以下是使用YOLOv3进行人脸检测的代码示例:
```python
import cv2
import numpy as np
# 加载YOLOv3模型
net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights')
# 获取YOLOv3输出层
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 加载图像
img = cv2.imread('test.jpg')
# 缩放图像以适应网络输入大小
img = cv2.resize(img, None, fx=0.4, fy=0.4)
# 获取图像尺寸
height, width, channels = img.shape
# 将图像转换为Blob格式
blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), swapRB=True, crop=False)
# 运行YOLOv3模型
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:
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_SIMPLEX
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(img, 'Face', (x, y - 10), font, 0.5, (0, 255, 0), 2)
# 显示图像
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这个代码使用了OpenCV的DNN模块来加载YOLOv3模型,然后对一张图像进行了人脸检测并将结果绘制在图像上。请注意,这个示例代码只能检测单张图像中的人脸,如果需要检测多张图像中的人脸,需要稍微修改代码。