Spaces:
No application file
No application file
Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
import cv2
|
4 |
+
import pickle
|
5 |
+
from tensorflow.keras.models import load_model
|
6 |
+
from tensorflow.keras.preprocessing.image import img_to_array
|
7 |
+
|
8 |
+
# Load the model and the label binarizer
|
9 |
+
model = load_model('cnn_model.h5')
|
10 |
+
label_binarizer = pickle.load(open('label_transform.pkl', 'rb'))
|
11 |
+
|
12 |
+
# Function to convert images to array
|
13 |
+
def convert_image_to_array(image):
|
14 |
+
try:
|
15 |
+
image = cv2.imdecode(np.frombuffer(image, np.uint8), cv2.IMREAD_COLOR)
|
16 |
+
if image is not None:
|
17 |
+
image = cv2.resize(image, (256, 256))
|
18 |
+
return img_to_array(image)
|
19 |
+
else:
|
20 |
+
return np.array([])
|
21 |
+
except Exception as e:
|
22 |
+
print(f"Error: {e}")
|
23 |
+
return None
|
24 |
+
|
25 |
+
def predict_image(image):
|
26 |
+
try:
|
27 |
+
image_array = convert_image_to_array(image)
|
28 |
+
|
29 |
+
if image_array.size == 0:
|
30 |
+
return "Invalid image"
|
31 |
+
|
32 |
+
# Normalize the image
|
33 |
+
image_array = np.array(image_array, dtype=np.float16) / 255.0
|
34 |
+
|
35 |
+
# Ensure the image_array has the correct shape (1, 256, 256, 3)
|
36 |
+
image_array = np.expand_dims(image_array, axis=0)
|
37 |
+
|
38 |
+
# Make a prediction
|
39 |
+
prediction = model.predict(image_array)
|
40 |
+
predicted_class = label_binarizer.inverse_transform(prediction)[0]
|
41 |
+
|
42 |
+
return predicted_class
|
43 |
+
except Exception as e:
|
44 |
+
return str(e)
|
45 |
+
|
46 |
+
# Define Gradio interface
|
47 |
+
interface = gr.Interface(
|
48 |
+
fn=predict_image,
|
49 |
+
inputs=gr.Image(type="numpy"),
|
50 |
+
outputs="text",
|
51 |
+
title="Image Classification",
|
52 |
+
description="Upload an image to get the predicted class."
|
53 |
+
)
|
54 |
+
|
55 |
+
if __name__ == "__main__":
|
56 |
+
interface.launch(share=True)
|