Views
No views yet
1
2# Use a pipeline as a high-level helper
3from PIL import Image
4from transformers import pipeline
5
6img = Image.open("<path_to_image_file>")
7classifier = pipeline("image-classification", model="Falconsai/nsfw_image_detection")
8classifier(img)
91
2# Load model directly
3import torch
4from PIL import Image
5from transformers import AutoModelForImageClassification, ViTImageProcessor
6
7img = Image.open("<path_to_image_file>")
8model = AutoModelForImageClassification.from_pretrained("Falconsai/nsfw_image_detection")
9processor = ViTImageProcessor.from_pretrained('Falconsai/nsfw_image_detection')
10with torch.no_grad():
11 inputs = processor(images=img, return_tensors="pt")
12 outputs = model(**inputs)
13 logits = outputs.logits
14
15predicted_label = logits.argmax(-1).item()
16model.config.id2label[predicted_label]
171
2import os
3import matplotlib.pyplot as plt
4from PIL import Image
5import numpy as np
6import onnxruntime as ort
7import json # Added import for json
8
9# Predict using YOLOv9 model
10def predict_with_yolov9(image_path, model_path, labels_path, input_size):
11 """
12 Run inference using the converted YOLOv9 model on a single image.
13
14 Args:
15 image_path (str): Path to the input image file.
16 model_path (str): Path to the ONNX model file.
17 labels_path (str): Path to the JSON file containing class labels.
18 input_size (tuple): The expected input size (height, width) for the model.
19
20 Returns:
21 str: The predicted class label.
22 PIL.Image.Image: The original loaded image.
23 """
24 def load_json(file_path):
25 with open(file_path, "r") as f:
26 return json.load(f)
27
28 # Load labels
29 labels = load_json(labels_path)
30
31 # Preprocess image
32 original_image = Image.open(image_path).convert("RGB")
33 image_resized = original_image.resize(input_size, Image.Resampling.BILINEAR)
34 image_np = np.array(image_resized, dtype=np.float32) / 255.0
35 image_np = np.transpose(image_np, (2, 0, 1)) # [C, H, W]
36 input_tensor = np.expand_dims(image_np, axis=0).astype(np.float32)
37
38 # Load YOLOv9 model
39 session = ort.InferenceSession(model_path)
40 input_name = session.get_inputs()[0].name
41 output_name = session.get_outputs()[0].name # Assuming classification output
42
43 # Run inference
44 outputs = session.run([output_name], {input_name: input_tensor})
45 predictions = outputs[0]
46
47 # Postprocess predictions (assuming classification output)
48 # Adapt this section if your model output is different (e.g., detection boxes)
49 predicted_index = np.argmax(predictions)
50 predicted_label = labels[str(predicted_index)] # Assumes labels are indexed by string numbers
51
52 return predicted_label, original_image
53
54# Display prediction for a single image
55def display_single_prediction(image_path, model_path, labels_path, input_size):
56 """
57 Predicts the class for a single image and displays the image with its prediction.
58
59 Args:
60 image_path (str): Path to the input image file.
61 model_path (str): Path to the ONNX model file.
62 labels_path (str): Path to the JSON file containing class labels.
63 input_size (tuple): The expected input size (height, width) for the model.
64 """
65 try:
66 # Run prediction
67 prediction, img = predict_with_yolov9(image_path, model_path, labels_path, input_size)
68
69 # Display image and prediction
70 fig, ax = plt.subplots(1, 1, figsize=(8, 8)) # Create a single plot
71 ax.imshow(img)
72 ax.set_title(f"Prediction: {prediction}", fontsize=14)
73 ax.axis("off") # Hide axes ticks and labels
74
75 plt.tight_layout()
76 plt.show()
77
78 except FileNotFoundError:
79 print(f"Error: Image file not found at {image_path}")
80 except Exception as e:
81 print(f"An error occurred: {e}")
82
83
84# --- Main Execution ---
85
86# Paths and parameters - **MODIFY THESE**
87single_image_path = "path/to/your/single_image.jpg" # <--- Replace with the actual path to your image file
88model_path = "path/to/your/yolov9_model.onnx" # <--- Replace with the actual path to your ONNX model
89labels_path = "path/to/your/labels.json" # <--- Replace with the actual path to your labels JSON file
90input_size = (224, 224) # Standard input size, adjust if your model differs
91
92# Check if the image file exists before proceeding (optional but recommended)
93if os.path.exists(single_image_path):
94 # Run prediction and display for the single image
95 display_single_prediction(single_image_path, model_path, labels_path, input_size)
96else:
97 print(f"Error: The specified image file does not exist: {single_image_path}")
981
2- 'eval_loss': 0.07463177293539047,
3- 'eval_accuracy': 0.980375,
4- 'eval_runtime': 304.9846,
5- 'eval_samples_per_second': 52.462,
6- 'eval_steps_per_second': 3.279
7