Commit
·
07302a4
1
Parent(s):
ea93bd5
Create onnx_barebones_inference.py
Browse files- onnx_barebones_inference.py +126 -0
onnx_barebones_inference.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import onnxruntime as ort
|
| 2 |
+
import numpy as np
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import requests
|
| 6 |
+
import io
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
# CONFIG SECTION
|
| 10 |
+
ONNX_MODEL_PATH = "./lsnet_xl_artist-dynamo-opset18_merged.onnx"
|
| 11 |
+
CSV_PATH = "./class_mapping.csv"
|
| 12 |
+
IMAGE_URL = "https://cdn.donmai.us/sample/9f/bb/__vampire_s_sister_original_drawn_by_gogalking__sample-9fbb30aa76bdc8242a1c122d3d6b41d9.jpg"
|
| 13 |
+
IMAGE_SIZE = (224, 224)
|
| 14 |
+
|
| 15 |
+
TOP_K = 5
|
| 16 |
+
PREDICTION_THRESHOLD = 0.0
|
| 17 |
+
# ------------------------------------------------------------
|
| 18 |
+
|
| 19 |
+
def preprocess_image_from_url(image_url, size=(224, 224)):
|
| 20 |
+
"""
|
| 21 |
+
Downloads an image from a URL, preprocesses it, and prepares it for the model.
|
| 22 |
+
"""
|
| 23 |
+
try:
|
| 24 |
+
response = requests.get(image_url)
|
| 25 |
+
response.raise_for_status() # Raise an exception for bad status codes
|
| 26 |
+
image_bytes = io.BytesIO(response.content)
|
| 27 |
+
image = Image.open(image_bytes).convert("RGB")
|
| 28 |
+
except requests.exceptions.RequestException as e:
|
| 29 |
+
print(f"Error: Failed to download image from URL '{image_url}'.\nDetails: {e}")
|
| 30 |
+
sys.exit(1)
|
| 31 |
+
except Exception as e:
|
| 32 |
+
print(f"Error: Could not process the downloaded image. It may not be a valid image file.\nDetails: {e}")
|
| 33 |
+
sys.exit(1)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# Resize the image
|
| 37 |
+
image = image.resize(size, Image.Resampling.LANCZOS)
|
| 38 |
+
|
| 39 |
+
# Convert image to numpy array and scale to [0, 1]
|
| 40 |
+
image_np = np.array(image, dtype=np.float32) / 255.0
|
| 41 |
+
|
| 42 |
+
# Define ImageNet mean and standard deviation for normalization
|
| 43 |
+
mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
|
| 44 |
+
std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
|
| 45 |
+
|
| 46 |
+
# Normalize the image
|
| 47 |
+
normalized_image = (image_np - mean) / std
|
| 48 |
+
|
| 49 |
+
# Transpose the dimensions from (H, W, C) to (C, H, W)
|
| 50 |
+
transposed_image = normalized_image.transpose((2, 0, 1))
|
| 51 |
+
|
| 52 |
+
# Add a batch dimension to create a shape of (1, C, H, W)
|
| 53 |
+
batched_image = np.expand_dims(transposed_image, axis=0)
|
| 54 |
+
|
| 55 |
+
return batched_image
|
| 56 |
+
|
| 57 |
+
def load_labels(csv_path):
|
| 58 |
+
"""
|
| 59 |
+
Loads the class labels from the provided CSV file into a dictionary,
|
| 60 |
+
handling the header row and stripping quotes from names.
|
| 61 |
+
"""
|
| 62 |
+
try:
|
| 63 |
+
df = pd.read_csv(csv_path)
|
| 64 |
+
if 'class_id' not in df.columns or 'class_name' not in df.columns:
|
| 65 |
+
print(f"Error: CSV file must have 'class_id' and 'class_name' columns.")
|
| 66 |
+
sys.exit(1)
|
| 67 |
+
df['class_name'] = df['class_name'].str.strip("'")
|
| 68 |
+
return dict(zip(df['class_id'], df['class_name']))
|
| 69 |
+
except FileNotFoundError:
|
| 70 |
+
print(f"Error: CSV file not found at '{csv_path}'")
|
| 71 |
+
sys.exit(1)
|
| 72 |
+
except Exception as e:
|
| 73 |
+
print(f"Error reading CSV file: {e}")
|
| 74 |
+
sys.exit(1)
|
| 75 |
+
|
| 76 |
+
def softmax(x):
|
| 77 |
+
"""Compute softmax values for a set of scores."""
|
| 78 |
+
e_x = np.exp(x - np.max(x))
|
| 79 |
+
return e_x / e_x.sum(axis=0)
|
| 80 |
+
|
| 81 |
+
def main():
|
| 82 |
+
"""
|
| 83 |
+
Main function to run the ONNX model inference.
|
| 84 |
+
"""
|
| 85 |
+
print("1. Loading class labels...")
|
| 86 |
+
labels = load_labels(CSV_PATH)
|
| 87 |
+
print(f" Loaded {len(labels)} labels.")
|
| 88 |
+
|
| 89 |
+
print("\n2. Downloading and preprocessing image from URL...")
|
| 90 |
+
input_tensor = preprocess_image_from_url(IMAGE_URL, IMAGE_SIZE)
|
| 91 |
+
print(f" Image shape: {input_tensor.shape}, Data type: {input_tensor.dtype}")
|
| 92 |
+
|
| 93 |
+
print("\n3. Initializing ONNX runtime session...")
|
| 94 |
+
try:
|
| 95 |
+
session = ort.InferenceSession(ONNX_MODEL_PATH, providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
|
| 96 |
+
input_name = session.get_inputs()[0].name
|
| 97 |
+
output_name = session.get_outputs()[0].name
|
| 98 |
+
print(" ONNX session created successfully.")
|
| 99 |
+
except Exception as e:
|
| 100 |
+
print(f"Error loading ONNX model: {e}")
|
| 101 |
+
sys.exit(1)
|
| 102 |
+
|
| 103 |
+
print("\n4. Running inference...")
|
| 104 |
+
results = session.run([output_name], {input_name: input_tensor})
|
| 105 |
+
logits = results[0][0]
|
| 106 |
+
print(" Inference complete.")
|
| 107 |
+
|
| 108 |
+
print("\n5. Processing results...")
|
| 109 |
+
probabilities = softmax(logits)
|
| 110 |
+
top_k_indices = np.argsort(probabilities)[-TOP_K:][::-1]
|
| 111 |
+
|
| 112 |
+
print(f"\n--- Predictions for image URL (Top K: {TOP_K}, Threshold: {PREDICTION_THRESHOLD:.1%}) ---")
|
| 113 |
+
|
| 114 |
+
predictions_found = 0
|
| 115 |
+
for i, index in enumerate(top_k_indices):
|
| 116 |
+
score = probabilities[index]
|
| 117 |
+
if score >= PREDICTION_THRESHOLD:
|
| 118 |
+
class_name = labels.get(index, f"Unknown Class #{index}")
|
| 119 |
+
print(f"Rank {i+1}: {class_name} (Score: {score:.2%})")
|
| 120 |
+
predictions_found += 1
|
| 121 |
+
|
| 122 |
+
if predictions_found == 0:
|
| 123 |
+
print("No predictions met the specified threshold.")
|
| 124 |
+
|
| 125 |
+
if __name__ == "__main__":
|
| 126 |
+
main()
|