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)