we are facing an problem with resnt18 model that is ONNX model validation failed: Field ‘name’ of by using this script import os
import cv2
import numpy as np
import onnxruntime as ort
import shutil
import onnx
Paths
input_image_dir = “/home/smarg/Documents/DataDrive/Script/CarClassification/Input/VehicleImage_till3aug”
output_dir = “/home/smarg/Documents/DataDrive/Script/CarClassification/OUTPUT/”
model_path = “/home/smarg/Documents/DataDrive/Script/CarClassification/Model/resnet18_vehiclemakenet_pruned.onnx”
Validate the ONNX model
try:
model = onnx.load(model_path)
onnx.checker.check_model(model)
print(“ONNX model is valid.”)
except Exception as e:
print(f"ONNX model validation failed: {e}")
exit(1) # Exit if the model is invalid
Create output directory if it doesn’t exist
os.makedirs(output_dir, exist_ok=True)
Load the ONNX model
try:
session = ort.InferenceSession(model_path)
input_name = session.get_inputs()[0].name
except Exception as e:
print(f"Failed to load ONNX model: {e}")
exit(1)
Label map
label_map = {
0: “acura”,
1: “audi”,
2: “bmw”,
3: “chevrolet”,
4: “chrysler”,
5: “dodge”,
6: “ford”,
7:“gmc”,
8:“honda”,
9:“hyundai”,
10:“infiniti”,
11:“jeep”,
12:“kia”,
13:“lexus”,
14:“mazda”,
15:“mercedes”,
16:“nissan”,
17:“subaru”,
18:“toyota”,
19:“volkswagen”
}
Mean values for preprocessing (example: BGR mean values)
mean_values = np.array([104.0, 117.0, 123.0])
def vehicle_make_infer(image_path, output_dir, confidence_threshold=0.9):
# Read the input image
image = cv2.imread(image_path)
# Check if the image is loaded correctly
if image is None:
print(f"Error: Unable to load image {image_path}")
return
# Prepare the image for the model
input_image = cv2.resize(image, (224, 224)) # Resize to 224x224
input_image = input_image.astype(np.float32)
input_image -= mean_values # Mean subtraction
input_image = input_image.transpose(2, 0, 1) # Channels first
input_image = np.expand_dims(input_image, axis=0)
# Run the model inference
try:
result = session.run(None, {input_name: input_image})
probabilities = result[0][0]
class_id = np.argmax(probabilities)
class_name = label_map[class_id]
confidence = probabilities[class_id]
print(f"Class id: {class_id}")
print(f"Confidence: {confidence}")
print(f"Class name: {class_name}")
# Create label and output directory
label = f"{class_name} ({confidence:.2f})"
output_cls_dir = os.path.join(output_dir, class_name)
output_file_path = os.path.join(output_cls_dir, f"{os.path.basename(image_path).split('.')[0]}_{label}.jpg")
os.makedirs(output_cls_dir, exist_ok=True)
# Save image if confidence is above the threshold
if confidence > confidence_threshold:
shutil.copy(image_path, output_file_path)
except Exception as e:
print(f"Error during inference: {e}")
def process_images_in_directory(input_dir, output_dir, confidence_threshold=0.9):
# Iterate over all image files in the input directory
for root, _, files in os.walk(input_dir):
for file in files:
if file.lower().endswith((‘.jpg’, ‘.jpeg’, ‘.png’)):
image_path = os.path.join(root, file)
vehicle_make_infer(image_path, output_dir, confidence_threshold)
def main():
process_images_in_directory(input_image_dir, output_dir)
if name == “main”:
main()
resolve the problem