yolov7detect获取图片
时间: 2023-10-21 10:05:05 浏览: 111
您可以使用以下代码获取图片并进行检测:
```python
import cv2
import torch
from models.experimental import attempt_load
from utils.general import non_max_suppression, scale_coords
from utils.torch_utils import select_device
# 加载模型
weights = 'yolov5s.pt'
device = select_device('')
model = attempt_load(weights, map_location=device)
stride = int(model.stride.max())
# 加载图片
img_path = 'test.jpg'
img = cv2.imread(img_path)
# 图片预处理
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = torch.from_numpy(img).to(device).float() / 255.0
if img.ndimension() == 3:
img = img.unsqueeze(0)
# 模型推理
pred = model(img)[0]
pred = non_max_suppression(pred, conf_thres=0.25, iou_thres=0.45)
# 处理预测结果
for det in pred:
if det is not None and len(det):
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], img.shape[2:]).round()
for *xyxy, conf, cls in reversed(det):
label = f'{model.names[int(cls)]} {conf:.2f}'
xyxy = [int(x) for x in xyxy]
cv2.rectangle(img, (xyxy[0], xyxy[1]), (xyxy[2], xyxy[3]), (255, 0, 0), 2)
cv2.putText(img, label, (xyxy[0], xyxy[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1)
# 显示结果
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文