要调用摄像头进行实时目标识别,您可以使用 OpenCV 库来获取视频流并使用 YOLOv8 模型进行实时推理。以下是一个基本的示例代码:

import cv2
import numpy as np

# 加载 YOLOv8 模型
net = cv2.dnn.readNet('yolov8.weights', 'yolov8.cfg')

# 获取输出层
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()

    # 将帧转换为 blob
    height, width, channels = frame.shape
    blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)

    # 将 blob 输入到模型中进行推理
    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(class_ids[i])
            confidence = confidences[i]
            color = (0, 255, 0)  # 边界框颜色 (BGR 格式)
            cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
            cv2.putText(frame, label + ' ' + str(round(confidence, 2)), (x, y - 10), font, 0.5, color, 2)

    # 显示视频流帧
    cv2.imshow('Real-time Object Detection', frame)
    if cv2.waitKey(1) == ord('q'):  # 按下 'q' 键退出
        break

# 释放摄像头和销毁窗口
cap.release()
cv2.destroyAllWindows()

请注意,您需要将 YOLOv8 的权重文件 ('yolov8.weights') 和配置文件 ('yolov8.cfg') 放在与代码文件相同的目录下,并根据您的实际文件名进行替换。

此示例代码将打开摄像头并实时显示视频流,同时在检测到的目标周围绘制边界框。您可以根据需要进行调整,例如更改置信度阈值、边界框颜色或添加其他处理步骤。


原文地址: https://www.cveoy.top/t/topic/quq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录