yolo python代码
时间: 2023-07-22 14:37:03 浏览: 170
15个YOLO算法的python代码示例集合.docx
以下是一个使用YOLOv3模型检测图像的Python代码示例:
```python
import cv2
import numpy as np
# 加载模型及其配置文件
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.0, (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]
x, y, w, h = boxes[i]
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 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
# 显示结果
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
此代码使用OpenCV的dnn模块来加载YOLOv3模型和其配置文件,并使用Numpy库来生成随机颜色。代码还使用cv2.imread()函数来加载图像,然后使用cv2.dnn.blobFromImage()函数将图像转换为模型输入所需的格式。最后,使用cv2.rectangle()和cv2.putText()函数绘制边框和类别标签,并使用cv2.imshow()函数显示结果。
阅读全文