File size: 1,540 Bytes
244c30f
 
 
 
 
 
95ea547
 
244c30f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import tensorflow as tf
from tensorflow.keras.utils import img_to_array, load_img
import numpy as np
import os

# Path model TFLite
model_path = os.path.join(os.path.dirname(__file__), "mobilenetv3_batik.tflite")


# Load interpreter TFLite
interpreter = tf.lite.Interpreter(model_path=model_path)
interpreter.allocate_tensors()

# Ambil detail input & output
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Label kelas
class_names = [
    'batik-bali', 'batik-betawi', 'batik-celup', 'batik-cendrawasih',
    'batik-ceplok', 'batik-ciamis', 'batik-garutan', 'batik-gentongan',
    'batik-kawung', 'batik-keraton', 'batik-lasem', 'batik-megamendung',
    'batik-parang', 'batik-pekalongan', 'batik-priangan', 'batik-sekar',
    'batik-sidoluhur', 'batik-sidomukti', 'batik-sogan', 'batik-tambal'
]

def predict_image(image_path):
    # Load & preprocess image
    image = load_img(image_path, target_size=(224, 224))
    image = img_to_array(image) / 255.0
    image = np.expand_dims(image, axis=0).astype(np.float32)

    # Set tensor input
    interpreter.set_tensor(input_details[0]['index'], image)

    # Jalankan inference
    interpreter.invoke()

    # Ambil tensor output
    predictions = interpreter.get_tensor(output_details[0]['index'])[0]
    max_index = np.argmax(predictions)
    predicted_class = class_names[max_index]
    confidence = float(predictions[max_index]) * 100

    return {
        "class": predicted_class,
        "confidence": round(confidence, 2)
    }