基于yolov8的图片识别的代码
时间: 2024-03-05 19:46:10 浏览: 139
基于YOLOv8的图片识别代码可以使用开源项目Darnet来实现。Darknet是一个用C语言编写的开源深度学习框架,支持多种目标检测算法,包括YOLO系列。
以下是一个基于YOLOv8的图片识别代码示例:
```python
import cv2
import numpy as np
# 加载YOLOv8模型
net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.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')
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)
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_SIMPLEX
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
confidence = confidences[i]
color = (0, 255, 0)
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
cv2.putText(image, label + ' ' + str(round(confidence, 2)), (x, y - 10), font, 0.5, color, 2)
# 显示结果
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请注意,上述代码中需要替换的部分包括YOLOv8模型的配置文件(yolov3.cfg)、权重文件(yolov3.weights)和类别标签文件(coco.names),以及待识别的图像文件(image.jpg)。
阅读全文
相关推荐















