Python 调用 YOLO ONNX
- 1 下载ONNX文件
- 2 Python代码
1 下载ONNX文件
ONNX下载地址
2 Python代码
import cv2
from ultralytics import YOLO
def check(yolo:str, path:str):
# 加载 YOLOv11
model = YOLO(yolo)
# 读取图片
img = cv2.imread(path)
# 推理(可以传文件路径或图像数组)
results = model(img)
# 取第一个结果(图像级别)
for result in results:
for box in result.boxes:
# 获取边框坐标并转换为整数
x1, y1, x2, y2 = map(int, box.xyxy[0])
# 获取类别编号和置信度
id = int(box.cls[0])
# 获取标签名称
label = result.names[id]
# 画矩形框
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
print('{}:{},\t {},{}\t {},{}'.format(id, label, x1, y1, x2, y2))
# 绘制文字
conf = float(box.conf[0])
text = f'{label} {conf:.2f}'
cv2.putText(img, text, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
# 显示图像
cv2.imshow("YOLOv11", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 可选:保存标注后的图像
cv2.imwrite("output.jpg", img)
def video(yolo:str):
# 加载 YOLO 模型(你也可以换成 yolov8n.pt / yolov8s.pt 等)
model = YOLO(yolo) # 更轻量,适合实时运行
# 打开默认摄像头
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
# 推理:BGR 图像直接传入
results = model(frame, verbose=False)
# 可视化结果:会自动绘制框和类别
annotated_frame = results[0].plot()
# 显示
cv2.imshow("YOLO Detection", annotated_frame)
# 按 Q 键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
def convert(yolo:str):
# 加载你的训练模型(.pt)
model = YOLO("runs/detect/train/weights/best.pt")
# 导出为 ONNX
return model.export(format="onnx", dynamic=True) # or simplify=True to simplify
check('yolo11n.pt','./11.png')
0: 320x640 6 persons, 11 cars, 650.3ms
Speed: 176.4ms preprocess, 650.3ms inference, 43.0ms postprocess per image at shape (1, 3, 320, 640)
2:car, 234,542 469,661
2:car, 637,224 795,324
2:car, 1580,571 1729,657
2:car, 585,558 714,647
2:car, 1223,236 1389,323
2:car, 1249,508 1510,626
0:person, 1414,195 1513,331
2:car, 275,177 509,314
0:person, 382,850 454,919
0:person, 1765,554 1868,659
0:person, 1065,520 1192,660
0:person, 861,525 952,657
2:car, 1725,244 1869,333
2:car, 937,166 1106,228
0:person, 964,538 1061,649
2:car, 872,489 1011,570
2:car, 897,509 1012,567
[Done] exited with code=0 in 39.085 seconds