computer-vision-gc7 / src /prediction.py
fernandobriann's picture
prediction.py update
95c828a verified
Raw
History Blame Contribute Delete
877 Bytes
import tensorflow as tf
import numpy as np
from PIL import Image
import json
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
MODEL_PATH = os.path.join(BASE_DIR, "model_fruit_cnn.h5")
LABEL_PATH = os.path.join(BASE_DIR, "class_labels.json")
# Load model
model = tf.keras.models.load_model(MODEL_PATH)
# Load label
with open(LABEL_PATH, "r") as f:
class_labels = json.load(f)
def preprocess_image(img):
img = img.convert("RGB")
img = img.resize((100, 100))
img_array = np.array(img) / 255.0
img_array = np.expand_dims(img_array, axis=0)
return img_array
def predict_image(img):
img_array = preprocess_image(img)
prediction = model.predict(img_array)
predicted_index = np.argmax(prediction)
confidence = float(np.max(prediction))
return class_labels[predicted_index], confidence