File size: 1,327 Bytes
2343e68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from keras.models import load_model
from PIL import Image, ImageOps
import numpy as np
import gradio as gr

# Load model and labels (once at startup)
np.set_printoptions(suppress=True)
model = load_model("keras_model.h5", compile=False)
class_names = open("labels.txt", "r").readlines()

def classify_image(input_img):
    """Classifies the input image using the loaded Keras model."""
    if input_img is None:
        return "No image provided"

    size = (224, 224)
    image = ImageOps.fit(Image.fromarray(np.uint8(input_img)), size, Image.Resampling.LANCZOS).convert("RGB")
    image_array = np.asarray(image)
    normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
    data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
    data[0] = normalized_image_array

    prediction = model.predict(data, verbose=0)
    index = np.argmax(prediction)
    class_name = class_names[index][2:].strip() # Remove index and strip whitespace
    confidence_score = prediction[0][index]
    return f"Class: {class_name}, Confidence: {confidence_score:.4f}"

demo = gr.Interface(
    classify_image,
    gr.Image(label="Upload image for classification", type="numpy"), # Input: Image upload, numpy type for efficiency
    gr.Text(label="Classification Result") # Output: Text classification result
)
demo.launch()