Spaces:
Sleeping
Sleeping
import gradio as gr | |
import pandas as pd | |
import numpy as np | |
import joblib | |
from skimage.measure import shannon_entropy | |
from skimage.color import rgb2hsv | |
from scipy.ndimage import generic_filter | |
import cv2 | |
from PIL import Image | |
# Function to extract features from the image | |
def extract_features(image): | |
# Convert PIL image to NumPy array | |
image = np.array(image) | |
# Extract RGB means | |
meanr = np.mean(image[:, :, 0]) # Red channel | |
meang = np.mean(image[:, :, 1]) # Green channel | |
meanb = np.mean(image[:, :, 2]) # Blue channel | |
# Convert to HSI and compute HHR | |
hsv_image = rgb2hsv(image) | |
hue = hsv_image[:, :, 0] | |
high_hue_pixels = np.sum(hue > 0.95) | |
total_pixels = hue.size | |
HHR = high_hue_pixels / total_pixels | |
# Convert to Grayscale | |
gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) | |
# Compute Entropy | |
Ent = shannon_entropy(gray_image) | |
# Compute Brightness | |
B = np.mean(gray_image) | |
# Sliding window for gray-level features | |
def g1_filter(window): | |
return window[4] - np.min(window) | |
def g2_filter(window): | |
return np.max(window) - window[4] | |
def g3_filter(window): | |
return window[4] - np.mean(window) | |
def g4_filter(window): | |
return np.std(window) | |
def g5_filter(window): | |
return window[4] | |
# Apply filters with 3x3 window | |
g1 = generic_filter(gray_image, g1_filter, size=3).mean() | |
g2 = generic_filter(gray_image, g2_filter, size=3).mean() | |
g3 = generic_filter(gray_image, g3_filter, size=3).mean() | |
g4 = generic_filter(gray_image, g4_filter, size=3).mean() | |
g5 = generic_filter(gray_image, g5_filter, size=3).mean() | |
# Return features | |
return { | |
"meanr": meanr, | |
"meang": meang, | |
"meanb": meanb, | |
"HHR": HHR, | |
"Ent": Ent, | |
"B": B, | |
"g1": g1, | |
"g2": g2, | |
"g3": g3, | |
"g4": g4, | |
"g5": g5, | |
} | |
# Function to check if the image is a valid file format | |
def check_image_format(image): | |
try: | |
# Try opening the image using PIL | |
img = Image.open(image) | |
img.verify() # Verify if it's a valid image file | |
return True | |
except Exception as e: | |
print(f"Error opening image: {e}") | |
return False | |
# Function to predict hemoglobin value | |
def predict_hemoglobin(age, gender, image): | |
try: | |
# Check if the image file is valid | |
if not check_image_format(image): | |
return "Error: The uploaded image file is not recognized or is corrupt. Please upload an image in JPG, PNG, BMP, or GIF format." | |
# Extract features from the image | |
features = extract_features(image) | |
# Ensure gender is encoded correctly (0 for female, 1 for male) | |
features['Gender'] = 1 if gender.lower() == 'M' else 0 | |
features['Age'] = age | |
# Create a DataFrame for features (do not include Hgb, as it's the predicted value) | |
features_df = pd.DataFrame([features]) | |
# Load the trained model, scaler, and label encoder | |
svr_model = joblib.load('svr_model(1).pkl') # Replace with the actual path to your model file | |
scaler = joblib.load('minmax_scaler.pkl') # Replace with the actual path to your scaler file | |
# Ensure that features_df matches the expected training feature set (without 'Hgb') | |
expected_columns = ['meanr', 'meang', 'meanb', 'HHR', 'Ent', 'B', 'g1', 'g2', 'g3', 'g4', 'g5', 'Age', 'Gender'] | |
for col in expected_columns: | |
if col not in features_df: | |
features_df[col] = 0 # Or some default value to match the expected columns. | |
features_df = features_df[expected_columns] # Ensure the correct order of columns | |
# Apply scaling (do not include 'Hgb' as it is the target) | |
features_df_scaled = scaler.transform(features_df) | |
# Predict hemoglobin using the trained SVR model | |
hemoglobin = svr_model.predict(features_df_scaled)[0] | |
return f"Predicted Hemoglobin Value: {hemoglobin:.2f}" | |
except Exception as e: | |
print(f"An error occurred during prediction: {e}") | |
return "An error occurred during prediction. Please try again." | |
# Gradio Interface setup | |
def create_gradio_interface(): | |
# Define the inputs and outputs for the Gradio interface | |
image_input = gr.Image(type="pil", label="Image (Upload Image)", interactive=True) | |
age_input = gr.Number(label="Age", value=25, precision=0) | |
gender_input = gr.Radio(choices=["Male", "Female"], label="Gender", value="Male") | |
# Set up the Gradio interface with the prediction function | |
iface = gr.Interface(fn=predict_hemoglobin, | |
inputs=[age_input, gender_input, image_input], | |
outputs="text", | |
live=True, | |
title="Hemoglobin Prediction") | |
iface.launch(share=True) # Set share=True to create a public link | |
# Run the Gradio app | |
if __name__ == "__main__": | |
create_gradio_interface() |