yolov3人脸检测代码
时间: 2023-07-28 15:06:38 浏览: 38
以下是使用YOLOv3进行人脸检测的代码示例,你需要先安装OpenCV和YOLOv3模型文件:
```python
import cv2
# 加载YOLOv3模型
net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights')
# 获取输出层名称
ln = net.getLayerNames()
ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 加载图像
image = cv2.imread('test.jpg')
# 获取图像尺寸
(H, W) = image.shape[:2]
# 构建blob
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)
# 设置模型输入
net.setInput(blob)
# 运行正向传递
layerOutputs = net.forward(ln)
# 初始化检测列表
boxes = []
confidences = []
classIDs = []
# 遍历每个输出层
for output in layerOutputs:
# 遍历每个检测
for detection in output:
# 提取类别ID和置信度
scores = detection[5:]
classID = np.argmax(scores)
confidence = scores[classID]
# 过滤掉置信度低的检测
if confidence > 0.5 and classID == 0:
# 计算检测框坐标
box = detection[0:4] * np.array([W, H, W, H])
(centerX, centerY, width, height) = box.astype('int')
# 计算检测框左上角坐标
x = int(centerX - (width / 2))
y = int(centerY - (height / 2))
# 更新检测列表
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
classIDs.append(classID)
# 应用非最大值抑制
idxs = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.3)
# 绘制检测框
if len(idxs) > 0:
for i in idxs.flatten():
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 显示输出图像
cv2.imshow('Output', image)
cv2.waitKey(0)
```
在上面的代码中,我们首先加载YOLOv3模型,然后读入待检测的图像。接着,我们将图像输入到模型中,运行正向传递,并获取检测结果。我们过滤掉置信度低的检测,并计算每个检测框的坐标。最后,我们应用非最大值抑制,并绘制检测框。