yolov8调用电脑摄像头
时间: 2023-10-31 13:06:08 浏览: 230
简单的调用电脑摄像头
5星 · 资源好评率100%
要使用YOLOv8调用电脑摄像头,需要先安装OpenCV和YOLOv8,并编写相应的代码。以下是一个简单的示例代码:
```python
import cv2
import numpy as np
# 加载YOLOv8模型
net = cv2.dnn.readNet("yolov8.weights", "yolov8.cfg")
# 获取摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取摄像头帧
ret, frame = cap.read()
# 对帧进行预处理
blob = cv2.dnn.blobFromImage(frame, 1/255, (416, 416), swapRB=True, crop=False)
# 将预处理后的帧输入到YOLOv8模型中进行检测
net.setInput(blob)
outs = net.forward(net.getUnconnectedOutLayersNames())
# 处理检测结果
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 = center_x - w // 2
y = center_y - h // 2
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([x, y, w, h])
# 绘制检测结果
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
for i in indices:
i = i[0]
box = boxes[i]
x, y, w, h = box
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 显示帧
cv2.imshow("frame", frame)
# 按下q键退出循环
if cv2.waitKey(1) == ord('q'):
break
# 释放摄像头并关闭窗口
cap.release()
cv2.destroyAllWindows()
```
阅读全文