yolov8 在检测图片中显示检测结果代码
时间: 2024-03-25 12:38:54 浏览: 144
以下是使用 YOLOv4 模型检测图片并显示检测结果的 Python 代码示例:
```python
import cv2
import numpy as np
# 加载 YOLOv4 模型
net = cv2.dnn.readNetFromDarknet("yolov4.cfg", "yolov4.weights")
# 获取类别标签
with open("coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
# 加载图片
img = cv2.imread("test.jpg")
# 调整尺寸并归一化
blob = cv2.dnn.blobFromImage(img, 1/255.0, (416, 416), swapRB=True, crop=False)
# 输入模型进行检测
net.setInput(blob)
output_layers = net.getUnconnectedOutLayersNames()
outs = net.forward(output_layers)
# 解析检测结果
conf_threshold = 0.5
nms_threshold = 0.4
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 > conf_threshold:
center_x = int(detection[0] * img.shape[1])
center_y = int(detection[1] * img.shape[0])
width = int(detection[2] * img.shape[1])
height = int(detection[3] * img.shape[0])
left = int(center_x - width / 2)
top = int(center_y - height / 2)
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([left, top, width, height])
# 非极大值抑制
indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)
# 显示检测结果
font_scale = 1
thickness = 1
color = (0, 255, 0)
for i in indices:
i = i[0]
box = boxes[i]
left = box[0]
top = box[1]
width = box[2]
height = box[3]
class_id = class_ids[i]
label = f"{classes[class_id]}: {confidences[i]:.2f}"
cv2.rectangle(img, (left, top), (left + width, top + height), color, thickness)
cv2.putText(img, label, (left, top - 5), cv2.FONT_HERSHEY_SIMPLEX, font_scale, color, thickness)
# 显示结果
cv2.imshow("Detection result", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`yolov4.cfg` 和 `yolov4.weights` 是 YOLOv4 模型的配置文件和权重文件,`coco.names` 是 COCO 数据集的类别标签文件。你需要根据自己的情况修改这些文件的路径。另外,`test.jpg` 是需要检测的图片文件,同样需要根据自己的情况修改路径。
阅读全文