Spaces:
Sleeping
Sleeping
import gradio as gr | |
import tensorflow as tf | |
from PIL import Image | |
import numpy as np | |
import cv2 | |
# Loading saved model | |
model = tf.keras.models.load_model('gender_recognition.h5') | |
def predict(input_image): | |
try: | |
# Convert PIL Image to OpenCV format (numpy array) | |
input_image = cv2.cvtColor(np.array(input_image), cv2.COLOR_RGB2BGR) | |
# Resizing and preprocessing input image | |
input_image = cv2.resize(input_image, (178, 218)) | |
input_image = np.array(input_image).astype(np.float32) / 255.0 | |
input_image = np.expand_dims(input_image, axis=0) # Add a dimension for the batch size | |
# Making prediction | |
prediction = model.predict(input_image) | |
# Postprocess prediction | |
labels = ['Female', 'Male'] | |
threshold = 0.5 # threshold for classifying as 'Male' | |
predicted_gender = 'Male' if prediction[0][1] > threshold else 'Female' | |
prediction_probability = prediction[0][1] if predicted_gender == 'Male' else prediction[0][0] | |
male_emoji = "\U0001F468" # Man emoji | |
female_emoji = "\U0001F469" # Woman emoji | |
selected_emoji = male_emoji if predicted_gender == 'Male' else female_emoji | |
# Combine the predicted gender and the probability into a single string | |
output = f"{selected_emoji} {predicted_gender}\n{prediction_probability * 100:.2f}% probability." | |
return output | |
except Exception as e: | |
return str(e) | |
# Creating Gradio interface | |
iface = gr.Interface( | |
fn=predict, | |
inputs=gr.inputs.Image(shape=(218, 178)), | |
outputs="text", | |
title = 'Image Recognition - Gender Detection with InceptionV3', | |
description="""<br> This model was trained to predict the gender of a person based on a photo. <br> | |
The training of this model can be seen on this <a href='https://www.kaggle.com/code/lusfernandotorres/gender-recognition-inceptionv3'>Kaggle notebook</a>. <br> | |
<br>Upload a photo to see the how the model predicts the gender of the person on it!""" | |
) | |
iface.launch() | |