image_Classifier / model.py
AlonBBar's picture
Add app and model scripts
59135b8
raw
history blame
1.06 kB
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense
from tensorflow.keras.models import Model
import tensorflow as tf
import numpy as np
from PIL import Image # <-- Add this import
def build_model(num_classes):
base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
base_model.trainable = False
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(128, activation='relu')(x)
output = Dense(num_classes, activation='softmax')(x)
model = Model(inputs=base_model.input, outputs=output)
return model
def predict(image: Image.Image):
"""
Predict the class of a given PIL image.
"""
image = image.resize((224, 224))
img_array = np.array(image) / 255.0
img_array = np.expand_dims(img_array, axis=0)
predictions = model.predict(img_array)
predicted_class = class_names[np.argmax(predictions)]
confidence = float(np.max(predictions))
return {predicted_class: confidence}