废话不多上直接上代码
import torch
from models.experimental import attempt_load
# 设置设备
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 定义 YOLOv5 模型
model = attempt_load(r'\best.pt', map_location=device) # 替换为你的本地路径
model = model.autoshape()
model = model.to(device).eval()
# 图像路径
image_path = r'img.jpg'
# 执行推理
results = model(image_path)
# 打印检测结果
for det in results.xyxy[0]:
print(f"类别: {int(det[5])}, 置信度: {det[4]}, 边界框: {det[:4]}")
根据注释提示和自己的需求更改即可