yolov8怎么调用摄像头
时间: 2023-10-01 07:12:27 浏览: 240
你可以使用 OpenCV 库来调用摄像头,并将视频流传递给 YOLOv8 模型进行目标检测。下面是一个示例代码:
```python
import cv2
import numpy as np
# 加载 YOLOv8 模型
net = cv2.dnn.readNet("yolov8.weights", "yolov8.cfg")
# 获取 YOLOv8 模型的输出层信息
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()
if not ret:
break
# 对视频流进行预处理
blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
# 运行 YOLOv8 模型进行目标检测
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] * frame.shape[1])
center_y = int(detection[1] * frame.shape[0])
w = int(detection[2] * frame.shape[1])
h = int(detection[3] * frame.shape[0])
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
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[class_ids[i]]
cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
cv2.putText(frame, label, (x, y - 10), font, 0.5, color, 2)
# 显示输出视频流
cv2.imshow("YOLOv8", frame)
if cv2.waitKey(1) == ord('q'):
break
# 释放摄像头和窗口
cap.release()
cv2.destroyAllWindows()
```
你需要将 `yolov8.weights` 和 `yolov8.cfg` 替换为你自己训练好的模型文件路径。这段代码会打开摄像头并实时显示目标检测的结果。按下 'q' 键即可退出程序。
阅读全文