Spaces:
Sleeping
Sleeping
Create model_utils.py
Browse files- model_utils.py +31 -0
model_utils.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# model_utils.py
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
class ImageClassifier:
|
| 7 |
+
def __init__(self, model_path):
|
| 8 |
+
self.model = tf.keras.models.load_model(model_path)
|
| 9 |
+
# Update these based on your model's requirements
|
| 10 |
+
self.input_size = (224, 224) # Example size, change as needed
|
| 11 |
+
self.class_names = ['class1', 'class2', 'class3'] # Replace with your class names
|
| 12 |
+
|
| 13 |
+
def preprocess_image(self, image):
|
| 14 |
+
"""Preprocess the image for your model"""
|
| 15 |
+
image = image.resize(self.input_size)
|
| 16 |
+
image_array = np.array(image)
|
| 17 |
+
image_array = image_array / 255.0 # Normalize if your model expects this
|
| 18 |
+
image_array = np.expand_dims(image_array, axis=0)
|
| 19 |
+
return image_array
|
| 20 |
+
|
| 21 |
+
def predict(self, image):
|
| 22 |
+
"""Make a prediction on the image"""
|
| 23 |
+
processed_image = self.preprocess_image(image)
|
| 24 |
+
predictions = self.model.predict(processed_image)
|
| 25 |
+
predicted_class = np.argmax(predictions[0])
|
| 26 |
+
confidence = np.max(predictions[0])
|
| 27 |
+
return {
|
| 28 |
+
'class': self.class_names[predicted_class],
|
| 29 |
+
'confidence': float(confidence),
|
| 30 |
+
'all_predictions': predictions.tolist()
|
| 31 |
+
}
|