yolov8物体识别实例
时间: 2023-09-29 14:04:49 浏览: 176
yolov8识别跟踪GUI
您好!您可以使用YOLOv3或YOLOv4进行物体识别,因为YOLOv8目前还没有正式发布。以下是一个使用YOLOv3进行物体识别的示例:
```python
import cv2
import numpy as np
# 加载类标签
classes = []
with open('coco.names', 'r') as f:
classes = [line.strip() for line in f.readlines()]
# 加载模型配置文件和权重文件
net = cv2.dnn.readNet('yolov3.weights', 'yolov3.cfg')
# 设置输入图像的大小和缩放因子
input_size = 416
scale = 0.00392
# 加载图像
image = cv2.imread('image.jpg')
height, width, channels = image.shape
# 创建输入图像的blob
blob = cv2.dnn.blobFromImage(image, scale, (input_size, input_size), (0, 0, 0), True, crop=False)
# 设置模型的输入
net.setInput(blob)
# 运行前向传播
outs = net.forward(net.getUnconnectedOutLayersNames())
# 初始化边界框、类别ID和置信度列表
boxes = []
class_ids = []
confidences = []
# 遍历每个输出层
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)
# 添加边界框、类别ID和置信度到列表中
boxes.append([x, y, w, h])
class_ids.append(class_id)
confidences.append(float(confidence))
# 使用非最大抑制来去除重叠的边界框
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 绘制边界框和类别标签
for i in indices:
i = i[0]
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(image, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# 显示结果图像
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这是一个简单的使用YOLOv3进行物体识别的实例。您需要下载YOLOv3的权重文件(yolov3.weights)和配置文件(yolov3.cfg),以及类标签文件(coco.names)。您还需要将要识别的图像命名为'image.jpg'并放置在同一目录下。您可以根据需要进行自定义设置和调整。希望对您有帮助!
阅读全文