Create sample.py
Browse files
sample.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tensorflow as tf
|
| 2 |
+
from tensorflow.keras.models import load_model
|
| 3 |
+
from tensorflow.keras.preprocessing import image
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
# --- Configuration ---
|
| 7 |
+
MODEL_PATH = 'weapon_classifier_final_tuned.keras'
|
| 8 |
+
IMAGE_PATH = './test_image.jpg'
|
| 9 |
+
IMG_SIZE = (224, 224)
|
| 10 |
+
# --- End Configuration ---
|
| 11 |
+
|
| 12 |
+
def load_and_preprocess_image(img_path, target_size):
|
| 13 |
+
"""Loads, resizes, and normalizes the image for prediction."""
|
| 14 |
+
img = image.load_img(img_path, target_size=target_size)
|
| 15 |
+
img_array = image.img_to_array(img)
|
| 16 |
+
# Add batch dimension: (H, W, C) -> (1, H, W, C)
|
| 17 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 18 |
+
# Normalize pixel values (0-255 -> 0-1)
|
| 19 |
+
processed_image = img_array / 255.0
|
| 20 |
+
return processed_image
|
| 21 |
+
|
| 22 |
+
def classify_image(model_path, image_path, img_size):
|
| 23 |
+
"""Loads the model, makes a prediction, and interprets the result."""
|
| 24 |
+
|
| 25 |
+
# Load the model
|
| 26 |
+
model = load_model(model_path)
|
| 27 |
+
print("Model loaded successfully.")
|
| 28 |
+
|
| 29 |
+
# Preprocess the image
|
| 30 |
+
input_image = load_and_preprocess_image(image_path, img_size)
|
| 31 |
+
|
| 32 |
+
# Make the prediction
|
| 33 |
+
prediction = model.predict(input_image)
|
| 34 |
+
|
| 35 |
+
# Interpret the result for binary classification
|
| 36 |
+
probability = prediction[0][0]
|
| 37 |
+
class_names = {0: 'Not a Weapon', 1: 'Weapon'}
|
| 38 |
+
|
| 39 |
+
if probability >= 0.5:
|
| 40 |
+
predicted_class = class_names[1]
|
| 41 |
+
confidence = probability * 100
|
| 42 |
+
else:
|
| 43 |
+
predicted_class = class_names[0]
|
| 44 |
+
confidence = (1 - probability) * 100
|
| 45 |
+
|
| 46 |
+
print("\n--- CLASSIFICATION RESULT ---")
|
| 47 |
+
print(f"Image: {os.path.basename(image_path)}")
|
| 48 |
+
print(f"Predicted Class: **{predicted_class}**")
|
| 49 |
+
print(f"Confidence: **{confidence:.2f}%**")
|
| 50 |
+
print("---------------------------\n")
|
| 51 |
+
|
| 52 |
+
# --- EXECUTE CLASSIFICATION ---
|
| 53 |
+
import os
|
| 54 |
+
classify_image(MODEL_PATH, IMAGE_PATH, IMG_SIZE)
|