帮我写一个用YOLOv5实现车辆与行人检测的代码
时间: 2023-08-28 15:39:09 浏览: 145
好的,以下是一个使用YOLOv5实现车辆与行人检测的Python代码示例:
```python
import torch
import cv2
import numpy as np
from PIL import Image
# Load YOLOv5 model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
# Set device to GPU if available
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
# Define class labels
class_labels = ['person', 'car']
# Load test image
image_path = 'test.jpg'
image = np.array(Image.open(image_path))
# Perform object detection
results = model(image, size=640)
predictions = results.pandas().xyxy[0]
# Draw bounding boxes around detected objects
for index, row in predictions.iterrows():
label = row['name']
if label in class_labels:
box = row[['xmin', 'ymin', 'xmax', 'ymax']].tolist()
cv2.rectangle(image, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)
cv2.putText(image, label, (box[0], box[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# Show image with detected objects
cv2.imshow('YOLOv5 Object Detection', image)
cv2.waitKey()
cv2.destroyAllWindows()
```
在上面的代码中,我们使用了`torch.hub.load`方法来加载预训练的YOLOv5模型。然后,我们将设备设置为GPU(如果可用),并将模型移动到该设备上。接下来,我们定义了要检测的类别标签(人和车)。然后,我们加载了一张测试图像,并对图像进行了对象检测。最后,我们在检测到的对象周围绘制了边界框,并显示了带有检测到的对象的图像。
阅读全文