yolov12推理代码
时间: 2025-03-10 18:00:53 浏览: 186
### YOLOv12 推理代码实例
对于YOLOv12模型的推理过程,通常遵循加载预训练权重、设置输入图像尺寸以及执行预测的标准流程。下面提供了一个基于Python环境下的YOLOv12推理代码示例:
```python
import torch
from yolov12.models.experimental import attempt_load
from yolov12.utils.general import non_max_suppression, scale_coords
from yolov12.utils.torch_utils import select_device
from PIL import Image
import numpy as np
def load_model(weights_path='yolov12.pt', device=''):
# 加载模型并将其移动到指定设备上(CPU/GPU)[^3]
device = select_device(device)
model = attempt_load(weights_path, map_location=device) # 自动下载或加载本地权重文件
return model, device
def preprocess_image(image_path, img_size=640):
# 图像预处理函数,调整大小至img_size×img_size,并转换成tensor格式[^3]
image = Image.open(image_path).convert('RGB')
ratio = min(img_size / max(image.size), img_size / min(image.size))
new_shape = (int(round(shape * ratio)) for shape in reversed(image.size))
resized_img = image.resize(new_shape, resample=Image.BILINEAR)
padded_img = np.full((img_size, img_size, 3), 114, dtype=np.uint8)
pad_w, pad_h = (img_size - new_shape[0]) // 2, (img_size - new_shape[1]) // 2
padded_img[pad_h:pad_h + new_shape[1], pad_w:pad_w + new_shape[0]] = resized_img
img_tensor = torch.from_numpy(padded_img).to(torch.float32) / 255.
img_tensor = img_tensor.permute(2, 0, 1).unsqueeze_(0)
return img_tensor, ratio, (pad_w, pad_h)
def run_inference(model, image_tensor, conf_thres=0.25, iou_thres=0.45, device=''):
pred = model(image_tensor.to(device))[0]
det = non_max_suppression(pred, conf_thres, iou_thres)[0]
if det is not None and len(det):
det[:, :4] = scale_coords(image_tensor.shape[2:], det[:, :4], original_shape).round()
return det.cpu().numpy()
if __name__ == '__main__':
weights = 'path_to_your_weights_file'
source_image = 'your_test_image.jpg'
model, device = load_model(weights_path=weights, device='')
input_tensor, _, _ = preprocess_image(source_image)
detections = run_inference(model, input_tensor)
print(detections)
```
此段代码展示了如何利用`attempt_load()`方法来加载YOLOv12模型及其对应的预训练参数;通过定义辅助性的`preprocess_image()`来进行数据准备;最后调用核心的`run_inference()`完成目标检测任务。
阅读全文
相关推荐


















