OpenCV 实时赛道识别 Python 代码示例
以下是使用 OpenCV 实时识别赛道的 Python 代码示例:
import cv2
import numpy as np
# 加载预训练的模型
net = cv2.dnn.readNet('yolov3.weights', 'yolov3.cfg')
# 加载类别标签
with open('coco.names', 'r') as f:
classes = f.read().splitlines()
# 获取输出层名称
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取摄像头帧
ret, frame = cap.read()
# 获取图像尺寸
height, width, channels = frame.shape
# 预处理图像
blob = cv2.dnn.blobFromImage(frame, 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_PLAIN
colors = np.random.uniform(0, 255, size=(len(classes), 3))
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
color = colors[i]
cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
cv2.putText(frame, label, (x, y - 5), font, 1, color, 1)
# 显示结果
cv2.imshow('Track Detection', frame)
# 按下 'q' 键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头和销毁窗口
cap.release()
cv2.destroyAllWindows()
请注意,你需要提前下载相应的预训练模型文件(yolov3.weights 和 yolov3.cfg)以及类别标签文件(coco.names)并将其与代码文件放在同一目录下。你可以在 OpenCV 官方网站上找到这些文件的下载链接。
原文地址: https://www.cveoy.top/t/topic/eKLR 著作权归作者所有。请勿转载和采集!