File size: 877 Bytes
4c8cb0b
 
 
 
95c828a
4c8cb0b
95c828a
 
 
4c8cb0b
95c828a
 
 
 
 
4c8cb0b
 
95c828a
4c8cb0b
95c828a
4c8cb0b
 
 
 
 
95c828a
4c8cb0b
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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