yolo3算法进行人体目标检测代码
时间: 2023-09-06 15:11:08 浏览: 144
下面是使用yolo3算法进行人体目标检测的Python代码,需要安装相应的库才能运行:
```python
import cv2
import numpy as np
# 加载yolo3模型
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
# 加载类别标签
classes = []
with open("coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
# 设置随机颜色
colors = np.random.uniform(0, 255, size=(len(classes), 3))
# 加载图像
img = cv2.imread("test.jpg")
# 获取图像的宽度和高度
height, width, _ = img.shape
# 对图像进行预处理
blob = cv2.dnn.blobFromImage(img, 1/255, (416, 416), swapRB=True, crop=False)
# 设置输入数据
net.setInput(blob)
# 执行前向传递
outs = net.forward(net.getUnconnectedOutLayersNames())
# 初始化检测结果
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:
# 计算检测框的位置
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)
# 添加到检测结果中
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([x, y, w, h])
# 对检测结果进行非最大抑制
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 绘制检测结果
for i in indices:
i = i[0]
box = boxes[i]
x = box[0]
y = box[1]
w = box[2]
h = box[3]
# 绘制检测框和类别标签
color = colors[class_ids[i]]
cv2.rectangle(img, (x, y), (x+w, y+h), color, 2)
cv2.putText(img, classes[class_ids[i]], (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
# 显示检测结果
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`yolov3.weights`和`yolov3.cfg`是yolo3模型的权重和配置文件,可以从官方网站下载。`coco.names`是yolo3模型的类别标签文件,也可以从官方网站下载。`test.jpg`是待检测的图像文件。执行代码后,将会在窗口中显示检测结果。
阅读全文