Spaces:
Sleeping
Sleeping
| from PIL import Image | |
| import numpy as np | |
| import cv2 # Necesario si vas a trabajar con np arrays en BGR | |
| def resize_image_for_print(image_np_bgr, target_dpi=300, target_long_side_cm=50): | |
| """ | |
| Redimensiona una imagen (numpy array BGR) para impresión a una resolución de 300 dpi | |
| y un lado más largo de 50 cm, sin alterar la estética. | |
| Args: | |
| image_np_bgr (np.ndarray): Imagen de entrada en formato NumPy BGR. | |
| target_dpi (int): Resolución deseada en DPI (píxeles por pulgada). | |
| target_long_side_cm (float): Longitud deseada del lado más largo en centímetros. | |
| Returns: | |
| np.ndarray: La imagen redimensionada en formato NumPy BGR. | |
| """ | |
| if not isinstance(image_np_bgr, np.ndarray): | |
| raise TypeError("La entrada debe ser un array de NumPy BGR.") | |
| # Convertir de BGR a RGB para PIL si fuera necesario, pero PIL puede trabajar con arrays directamente | |
| # Para simplicidad y consistencia, vamos a pasar de NumPy BGR a PIL RGB y luego de vuelta a NumPy BGR. | |
| img_pil_rgb = Image.fromarray(cv2.cvtColor(image_np_bgr, cv2.COLOR_BGR2RGB)) | |
| # 1. Calcular el tamaño en píxeles basado en el lado más largo deseado y el DPI | |
| # 1 pulgada = 2.54 cm | |
| target_long_side_inches = target_long_side_cm / 2.54 | |
| target_long_side_pixels = int(target_long_side_inches * target_dpi) | |
| # Obtener el ancho y alto actuales de la imagen PIL | |
| width, height = img_pil_rgb.size | |
| # Determinar cuál es el lado más largo de la imagen original | |
| if width > height: | |
| # El ancho es el lado más largo | |
| new_width = target_long_side_pixels | |
| new_height = int(height * (new_width / width)) | |
| else: | |
| # El alto es el lado más largo (o son iguales) | |
| new_height = target_long_side_pixels | |
| new_width = int(width * (new_height / height)) | |
| # 2. Redimensionar la imagen usando un filtro de alta calidad | |
| resized_img_pil_rgb = img_pil_rgb.resize((new_width, new_height), Image.LANCZOS) | |
| # Convertir de nuevo a NumPy BGR | |
| resized_np_rgb = np.array(resized_img_pil_rgb) | |
| resized_np_bgr = cv2.cvtColor(resized_np_rgb, cv2.COLOR_RGB2BGR) | |
| # Nota: Los metadatos de DPI no se pueden "incrustar" directamente en un np.ndarray. | |
| # Si realmente necesitas guardarlo con DPI para impresión, la función de guardado | |
| # debe hacerse fuera de aquí, quizás en el main.py cuando se exporta el resultado final. | |
| # Por ahora, esta función solo devuelve la imagen redimensionada. | |
| return resized_np_bgr |