yolov8检测图片
时间: 2023-09-22 11:11:08 浏览: 141
YOLOv8实战案例集锦.pdf
你可以使用以下代码来使用YOLOv4模型检测图片:
```python
import cv2
import numpy as np
# 加载YOLOv4模型
net = cv2.dnn.readNetFromDarknet('yolov4.cfg', 'yolov4.weights')
# 获取所有层的名称
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 加载类别标签
classes = []
with open('coco.names', 'r') as f:
classes = [line.strip() for line in f.readlines()]
# 加载待检测的图片
image = cv2.imread('image.jpg')
# 图片预处理
blob = cv2.dnn.blobFromImage(image, 1/255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
# 前向推理,获取检测结果
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] * image.shape[1])
center_y = int(detection[1] * image.shape[0])
width = int(detection[2] * image.shape[1])
height = int(detection[3] * image.shape[0])
# 边界框的左上角坐标
x = int(center_x - width / 2)
y = int(center_y - height / 2)
boxes.append([x, y, width, height])
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, width, height = boxes[i]
label = classes[class_ids[i]]
confidence = confidences[i]
color = colors[class_ids[i]]
cv2.rectangle(image, (x, y), (x + width, y + height), color, 2)
cv2.putText(image, f'{label} {confidence:.2f}', (x, y - 10), font, 1, color, 2)
# 显示检测结果
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在运行代码之前,请确保已经下载了YOLOv4的配置文件(yolov4.cfg)和权重文件(yolov4.weights),并将其放在同一目录下。同时,还需要下载COCO数据集的标签文件(coco.names)。
你可以将待检测的图片替换为自己的图片,并对代码进行必要的修改(例如文件名、模型路径等)。运行代码后,你将会在窗口中看到检测结果的可视化。
阅读全文