yolo v8 webcam read
时间: 2023-10-31 08:58:03 浏览: 45
你可以使用以下代码片段来使用YOLO v8模型读取网络摄像头中的视频流:
```python
import cv2
import numpy as np
# 加载YOLO v3配置和权重文件
net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights')
# 获取输出层的名称
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 = 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 = []
height, width, channels = frame.shape
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 = (255, 0, 0) # 边界框颜色为红色
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('YOLO v3', frame)
# 按下q键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
```
请确保你已经下载了YOLO v3的配置文件(`yolov3.cfg`)和权重文件(`yolov3.weights`),并将其放在与你的代码相同的目录下。此代码将从网络摄像头中读取视频流,并在检测到的对象周围绘制边界框。