Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import cv2 | |
| import numpy as np | |
| from PIL import Image | |
| # Configuración de la página con límite de carga | |
| st.set_page_config( | |
| page_title="CV Edge Detector - Beau's Lab", | |
| layout="wide" | |
| ) | |
| # Configuración para Hugging Face Spaces | |
| MAX_FILE_SIZE = 5 * 1024 * 1024 # 5 MB en bytes | |
| def process_image(image, low_threshold, high_threshold): | |
| """ | |
| Aplica el algoritmo de Canny para detección de bordes. | |
| """ | |
| # Convertir imagen de PIL a formato OpenCV (numpy array BGR) | |
| img_array = np.array(image.convert('RGB')) | |
| img_cv = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR) | |
| # Convertir a escala de grises | |
| gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY) | |
| # Aplicar Canny | |
| edges = cv2.Canny(gray, low_threshold, high_threshold) | |
| return edges | |
| def main(): | |
| st.set_page_config(page_title="CV Edge Detector - Beau's Lab", layout="wide") | |
| st.title("🛠️ Computer Vision Lab: Edge Detection") | |
| st.write("Bienvenido. Sube una imagen para analizar sus gradientes espaciales.") | |
| # Sidebar para parámetros (Hiperparámetros del algoritmo) | |
| st.sidebar.header("Configuración de Algoritmo") | |
| low_thresh = st.sidebar.slider("Umbral Bajo (Low)", 0, 255, 100) | |
| high_thresh = st.sidebar.slider("Umbral Alto (High)", 0, 255, 200) | |
| uploaded_file = st.file_uploader("Elige una imagen...( max size 4MB )", type=["jpg", "jpeg", "png"]) | |
| if uploaded_file is not None: | |
| # Validar tamaño del archivo | |
| file_size = uploaded_file.size | |
| if file_size > MAX_FILE_SIZE: | |
| st.error(f"⚠️ El archivo es demasiado grande ({file_size / 1024 / 1024:.2f} MB). Por favor, sube una imagen menor a 5 MB.") | |
| return | |
| try: | |
| # Cargar imagen | |
| image = Image.open(uploaded_file) | |
| # Redimensionar si es muy grande (optimización adicional) | |
| max_dimension = 1920 | |
| if max(image.size) > max_dimension: | |
| st.warning(f"Imagen grande detectada. Redimensionando para mejor rendimiento...") | |
| ratio = max_dimension / max(image.size) | |
| new_size = tuple([int(x * ratio) for x in image.size]) | |
| image = image.resize(new_size, Image.Resampling.LANCZOS) | |
| # Crear dos columnas para comparar | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.header("Imagen Original") | |
| st.image(image, use_container_width=True) | |
| with col2: | |
| st.header("Detección de Bordes (Canny)") | |
| # Procesamiento | |
| with st.spinner('Procesando...'): | |
| processed_img = process_image(image, low_thresh, high_thresh) | |
| st.image(processed_img, use_container_width=True, clamp=True) | |
| st.success("¡Procesamiento completado con éxito!") | |
| except Exception as e: | |
| st.error(f"Error al procesar la imagen: {str(e)}") | |
| st.info("Por favor, intenta con otra imagen.") | |
| else: | |
| st.info("Esperando que se suba una imagen...") | |
| st.markdown(""" | |
| ### Instrucciones: | |
| - Formatos soportados: JPG, JPEG, PNG | |
| - Tamaño máximo: 5 MB | |
| - Para mejores resultados, usa imágenes con objetos definidos | |
| """) | |
| if __name__ == "__main__": | |
| main() |