Performing inference using onnx #213
Rhroan
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
#!/usr/bin/env python3
"""
2025/07/09 = Test completed
inference_full_onnx.py
Supports inference for a single image or batch from a folder, using an exported ONNX model (yolov9_full.onnx)
that includes complete post-processing (decode + NMS).
Automatically detects whether to use GPU (CUDAExecutionProvider).
Falls back to CPUExecutionProvider if CUDA is unavailable.
When displaying, the window will be resized to 1/2 of the original image dimensions.
"""
import cv2
import numpy as np
import onnxruntime as ort
from PIL import Image
from pathlib import Path
from datetime import datetime
---------- Configuration ----------
#IMAGE_PATH = "D:/Work/Study/Yolo/Image_Source/ColorSticker/images/val/CamerA_C_20250616_155413.jpg"
IMAGE_PATH = "D:/Work/Study/Yolo/Image_Source/ColorSticker/images/val"
ONNX_PATH = "yolov9_full.onnx"
IMG_SIZE = 640
CLASS_LIST = ["Sticker"] # Single class label
---------- Utility Functions ----------
def letterbox(pil_img, size=IMG_SIZE, color=(114,114,114)):
"""
Resize the image with aspect ratio preserved and pad to square (same as training).
Returns:
- padded PIL.Image (size×size)
- r float: scaling ratio
- pad_w int : width padding (left-right)
- pad_h int : height padding (top-bottom)
"""
w0, h0 = pil_img.size
r = min(size / w0, size / h0)
nw, nh = int(w0 * r), int(h0 * r)
resized = pil_img.resize((nw, nh), Image.LANCZOS)
pad_w, pad_h = (size - nw) // 2, (size - nh) // 2
canvas = Image.new("RGB", (size, size), color)
canvas.paste(resized, (pad_w, pad_h))
return canvas, r, pad_w, pad_h
def get_image_list(path_str):
"""
If path_str is a file, return [path_str];
If it's a folder, return a list of all common image file paths.
"""
p = Path(path_str)
if p.is_file():
return [p]
elif p.is_dir():
exts = {".jpg", ".jpeg", ".png", ".bmp"}
return sorted([x for x in p.iterdir() if x.suffix.lower() in exts])
else:
raise FileNotFoundError(f"Path not found: {path_str}")
---------- Main Flow ----------
def main():
# 1) Prepare image list
img_paths = get_image_list(IMAGE_PATH)
if name == "main":
main()
Beta Was this translation helpful? Give feedback.
All reactions