python实现yolo目标检测代码
时间: 2023-08-06 19:04:19 浏览: 296
以下是一个基本的Python代码示例,用于使用YOLO进行目标检测。
```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()]
# 加载图像
img = cv2.imread("image.jpg")
height, width, channels = img.shape
# 构建输入图片的blob格式
blob = cv2.dnn.blobFromImage(img, 1/255.0, (416, 416), swapRB=True, crop=False)
# 设置输入层
net.setInput(blob)
# 获取每个输出层的名称和大小
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
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:
# 中心点坐标和边界框大小
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
colors = np.random.uniform(0, 255, size=(len(classes), 3))
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
color = colors[class_ids[i]]
cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
cv2.putText(img, label, (x, y + 30), font, 3, color, 3)
# 显示图像
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`yolov3.weights`和`yolov3.cfg`是预训练的权重文件和配置文件,可以从YOLO官网下载。`coco.names`是目标类别标签文件,在本例中使用了COCO数据集的标签,也可以使用其他数据集的标签。`image.jpg`是要进行目标检测的图像文件,可以替换为其他文件路径。
阅读全文