yolo v8 webcam 讀出參數
时间: 2023-09-30 15:11:22 浏览: 48
你可以使用YOLOv4或YOLOv5通过Webcam读取参数。首先,确保你已经安装了必要的库,如OpenCV和YOLO。
下面是一个示例代码,用于使用YOLOv4检测Webcam中的对象并打印出参数:
```python
import cv2
import numpy as np
# 加载YOLOv4模型
net = cv2.dnn.readNetFromDarknet('yolov4.cfg', 'yolov4.weights')
# 获取YOLOv4网络输出层的名称
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 打开Webcam
cap = cv2.VideoCapture(0)
while True:
_, frame = cap.read()
# 对帧进行预处理
height, width, channels = frame.shape
blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
# 将预处理后的帧输入到YOLOv4模型中
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)
# 存储参数
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([x, y, w, h])
# 打印参数
print("Class IDs:", class_ids)
print("Confidences:", confidences)
print("Boxes:", boxes)
# 绘制检测框和类别标签
class_names = ['class1', 'class2', 'class3'] # 替换为你的类别名称
colors = np.random.uniform(0, 255, size=(len(class_names), 3))
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = f"{class_names[class_ids[i]]}: {confidences[i]:.2f}"
color = colors[class_ids[i]]
cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
cv2.putText(frame, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
# 显示帧
cv2.imshow("YOLOv4", frame)
if cv2.waitKey(1) == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
```
请注意,你需要将`yolov4.cfg`和`yolov4.weights`替换为你实际的YOLOv4模型文件路径。同时,你也可以在`class_names`列表中替换为你自己的类别名称。
运行这段代码后,控制台将打印出检测到的对象的类别ID、置信度和边界框坐标参数,并且窗口中将显示实时的Webcam画面及检测结果。