Spaces:
Runtime error

SkinCancer / app.py
WILBER261002's picture
Update app.py
31964cf verified
Raw History Blame Contribute Delete
2.66 kB
from fastapi import FastAPI, File, UploadFile, HTTPException
from PIL import Image
import numpy as np
import tensorflow as tf
from io import BytesIO
import cv2
# Cargar el modelo previamente entrenado
def load_model():
model = tf.keras.models.load_model('cancer_model.h5')
return model
# Funci贸n para procesar las im谩genes (similar al c贸digo de Colab)
def preprocess_image(image):
try:
# Convertir la imagen a un arreglo numpy
image_np = np.array(image)
# Convertir la imagen a escala de grises
grayscale = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
# Filtro Gaussiano para suavizar
smoothed = cv2.GaussianBlur(grayscale, (5, 5), 0)
# Resaltado de bordes con Sobel
sobelx = cv2.Sobel(smoothed, cv2.CV_64F, 1, 0, ksize=3)
sobely = cv2.Sobel(smoothed, cv2.CV_64F, 0, 1, ksize=3)
sobel = cv2.magnitude(sobelx, sobely)
# Normalizar la imagen a rango 0-255
sobel_normalized = cv2.normalize(sobel, None, 0, 255, cv2.NORM_MINMAX)
sobel_normalized = sobel_normalized.astype('uint8')
# Redimensionar la imagen a 64x64
resized = cv2.resize(sobel_normalized, (64, 64))
# Convertir la imagen a 3 canales (RGB)
resized_rgb = cv2.cvtColor(resized, cv2.COLOR_GRAY2RGB)
# Normalizar la imagen
normalized_image = resized_rgb / 255.0
return np.expand_dims(normalized_image, axis=0) # A帽adir la dimensi贸n del batch
except Exception as e:
print(f"Error procesando la imagen: {e}")
return None
# Iniciar la aplicaci贸n FastAPI
app = FastAPI()
# Cargar el modelo previamente entrenado
model = load_model()
# Ruta para realizar la predicci贸n
@app.post("/predict/")
async def predict_image(file: UploadFile = File(...)):
try:
# Leer el archivo de imagen subido
contents = await file.read()
image = Image.open(BytesIO(contents))
# Procesar la imagen
processed_image = preprocess_image(image)
if processed_image is not None:
# Realizar la predicci贸n utilizando el modelo cargado
prediction = model.predict(processed_image)
# Interpretar la predicci贸n
result = "Maligno" if prediction >= 0.5 else "Benigno"
confidence = prediction[0][0]
# Devolver la respuesta
return {"prediction": result, "confidence": float(confidence)}
else:
raise HTTPException(status_code=400, detail="Error en el preprocesamiento de la imagen")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))