基于yolo v5的危险物品检测代码
时间: 2023-11-28 07:48:46 浏览: 143
基于yoloV5的x下光危险物物品识别推理代码带UI界面
5星 · 资源好评率100%
以下是使用Yolo v5进行危险物品检测的示例代码:
```python
import torch
import cv2
import numpy as np
from pathlib import Path
# Load YOLOv5s model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
# Define class names
classes = ['gun', 'knife', 'explosive']
# Load image
img_path = Path('path/to/image')
img = cv2.imread(str(img_path))
# Detect objects
results = model(img)
# Filter out dangerous objects
dangerous_results = []
for result in results.xyxy[0]:
if result[5] in [classes.index(c) for c in classes]:
dangerous_results.append(result)
# Draw bounding boxes
for result in dangerous_results:
x1, y1, x2, y2, _, cls = result
cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
cv2.putText(img, classes[int(cls)], (int(x1), int(y1)-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
# Show image
cv2.imshow('Dangerous Objects Detection', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个示例中,我们首先加载了Yolo v5S的预训练模型。然后定义了我们要检测的类别名称。接着读取了一张图片并使用模型进行检测。最后,我们过滤出了危险物品的检测结果,并在图片上绘制了边界框和类别标签。
阅读全文