YOLOV8 分析摄像头代码
时间: 2023-12-20 12:21:12 浏览: 35
以下是使用YOLOV8进行摄像头分析的示例代码:
```python
import cv2
import numpy as np
import time
# 加载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()]
# 加载类别标签
classes = []
with open("coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
# 设置摄像头
cap = cv2.VideoCapture(0)
# 循环读取摄像头帧
while True:
# 读取帧
ret, frame = cap.read()
# 调整帧大小并归一化像素值
resized = cv2.resize(frame, (416, 416))
normalized = resized / 255.0
# 转换为模型可处理的格式
blob = cv2.dnn.blobFromImage(normalized, scalefactor=1/255.0, size=(416, 416), mean=[0, 0, 0], swapRB=True, crop=False)
# 将数据送入模型进行预测
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] * frame.shape[1])
center_y = int(detection[1] * frame.shape[0])
width = int(detection[2] * frame.shape[1])
height = int(detection[3] * frame.shape[0])
left = int(center_x - width/2)
top = int(center_y - height/2)
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([left, top, width, height])
# 应用非极大值抑制
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 绘制检测结果
for i in indices:
i = i[0]
box = boxes[i]
left = box[0]
top = box[1]
width = box[2]
height = box[3]
cv2.rectangle(frame, (left, top), (left+width, top+height), (0, 255, 0), 2)
cv2.putText(frame, classes[class_ids[i]], (left+5, top+25), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
# 显示结果
cv2.imshow("YOLOV8", frame)
# 按下q键退出
if cv2.waitKey(1) == ord('q'):
break
# 释放摄像头并销毁所有窗口
cap.release()
cv2.destroyAllWindows()
```
请注意,此代码仅提供示例,您需要根据实际情况进行修改和调整。此外,您需要下载YOLOV8模型文件和类别标签文件,并将其放置在代码所在目录中。