用yolov8训练好的模型检测代码
时间: 2024-05-13 07:10:19 浏览: 100
当使用YOLOv8训练好的模型进行目标检测时,你需要编写一段代码来加载模型并进行检测。以下是一个简单的示例代码:
```python
import cv2
import numpy as np
# 加载YOLOv8模型
net = cv2.dnn.readNetFromDarknet('yolov8.cfg', 'yolov8.weights')
# 获取输出层信息
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 加载图像
image = cv2.imread('image.jpg')
height, width, channels = image.shape
# 对图像进行预处理
blob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0, 0, 0), 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] * 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])
# 非极大值抑制,去除重叠的检测结果
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 在图像上绘制检测结果
font = cv2.FONT_HERSHEY_SIMPLEX
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(class_ids[i])
confidence = confidences[i]
color = (255, 0, 0) # 检测框颜色
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
cv2.putText(image, label, (x, y - 10), font, 0.5, color, 2)
# 显示检测结果
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请注意,上述代码中的`yolov8.cfg`和`yolov8.weights`分别是YOLOv8模型的配置文件和权重文件,你需要将其替换为你自己训练好的模型的文件路径。此外,你还需要将`image.jpg`替换为你要进行检测的图像文件路径。
阅读全文