将yolov7的推理部分封装成函数
时间: 2023-05-12 20:03:57 浏览: 248
可以使用以下代码将 YOLOv7 的推理部分封装成函数:
```
import torch
import numpy as np
from models.experimental import attempt_load
from utils.general import non_max_suppression, scale_coords, xyxy2xywh
from utils.torch_utils import select_device
def yolov7_inference(img_path, conf_thres=0.25, iou_thres=0.45, device='cpu'):
# Load model
model = attempt_load('yolov7.pt', map_location=device)
# Set device
device = select_device(device)
# Load image
img = torch.from_numpy(np.array(Image.open(img_path)))
# Inference
img = img.to(device).float() / 255.0
img = img.unsqueeze(0)
pred = model(img)[0]
pred = non_max_suppression(pred, conf_thres, iou_thres)
# Post-processing
if pred[0] is not None:
pred[0] = scale_coords(img.shape[2:], pred[0][:, :4], img.shape[2:]).round()
pred[0][:, :4] = xyxy2xywh(pred[0][:, :4]).round()
return pred
```
这个函数接受一个图片路径作为输入,以及可选的置信度阈值、IOU 阈值和设备类型。它返回一个包含预测框的列表,每个预测框由左上角和右下角的坐标、置信度和类别 ID 组成。
阅读全文