File size: 1,688 Bytes
d75cc9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
50
51
52
53
54
55
56
57
import gradio as gr
import numpy as np
import cv2
import pickle
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import img_to_array

# Load the model and the label binarizer
model = load_model('cnn_model.h5')
label_binarizer = pickle.load(open('label_transform.pkl', 'rb'))

# Function to convert images to array
def convert_image_to_array(image):
    try:
        image = cv2.imdecode(np.frombuffer(image, np.uint8), cv2.IMREAD_COLOR)
        if image is not None:
            image = cv2.resize(image, (256, 256))
            return img_to_array(image)
        else:
            return np.array([])
    except Exception as e:
        print(f"Error: {e}")
        return None

def predict_image(image):
    try:
        image_array = convert_image_to_array(image)

        if image_array.size == 0:
            return "Invalid image"

        # Normalize the image
        image_array = np.array(image_array, dtype=np.float16) / 255.0

        # Ensure the image_array has the correct shape (1, 256, 256, 3)
        image_array = np.expand_dims(image_array, axis=0)

        # Make a prediction
        prediction = model.predict(image_array)
        predicted_class = label_binarizer.inverse_transform(prediction)[0]

        return predicted_class
    except Exception as e:
        return str(e)

# Define Gradio interface
interface = gr.Interface(
    fn=predict_image, 
    inputs=gr.Image(type="numpy"), 
    outputs="text",
    title="Image Classification",
    description="Upload an image to get the predicted class."
)

if __name__ == "__main__":
    interface.launch(share=True)