yoloV5 本地摄像头每隔几秒检测一次
时间: 2023-09-01 13:11:25 浏览: 180
您好!您可以使用YOLOv5模型来检测本地摄像头的实时视频流。以下是一个基本的示例代码,它每隔几秒钟从摄像头中获取一帧图像,并对图像进行目标检测:
```python
import cv2
from PIL import Image
import torch
from torchvision.transforms import functional as F
from models.experimental import attempt_load
from utils.general import non_max_suppression, scale_coords
from utils.datasets import letterbox
def detect(frame, model, device):
# 图像预处理
img = letterbox(frame, new_shape=640)[0]
img = img[:, :, ::-1].transpose(2, 0, 1)
img = np.ascontiguousarray(img)
img = torch.from_numpy(img).to(device).float() / 255.0
img = img.unsqueeze(0)
# 目标检测
pred = model(img)[0]
pred = non_max_suppression(pred, conf_thres=0.5, iou_thres=0.5)
# 处理检测结果
if len(pred) > 0:
pred = pred[0] # 只处理第一个预测结果
pred[:, :4] = scale_coords(img.shape[2:], pred[:, :4], frame.shape).round()
return pred
def main():
# 加载YOLOv5模型
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = attempt_load("yolov5s.pt", map_location=device)
model.to(device).eval()
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
# 每隔几秒检测一次
if cv2.waitKey(2000) & 0xFF == ord('q'):
break
# 进行目标检测
pred = detect(frame, model, device)
# 在图像上绘制检测结果
if len(pred) > 0:
for x1, y1, x2, y2, conf, cls in pred:
cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2)
cv2.putText(frame, str(cls), (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2)
# 显示图像
cv2.imshow('YOLOv5 Detection', frame)
# 释放摄像头和关闭窗口
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
```
上述代码使用了YOLOv5的Python实现,通过调用摄像头获取视频帧,并使用模型进行目标检测。代码中的`detect`函数用于对单帧图像进行目标检测,`main`函数中的`cv2.waitKey(2000)`表示每隔2秒检测一次。您可以根据需要调整检测的时间间隔。请确保已经安装了相关的依赖库,并且已经下载了YOLOv5的权重文件(`yolov5s.pt`)。
希望对您有帮助!如果您有任何其他问题,请随时提问。