Spaces:
Sleeping
Sleeping
Update app.py
Browse files207 unmodified lines208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316207 unmodified lines)if __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860, share=False, debug=True)```=== utils.py ===```pythonimport torchimport numpy as npfrom PIL import Imageimport matplotlibimport requestsfrom io import BytesIOdef load_image_from_url(url: str) -> Image.Image:"""Load an image from a URL.Args:url: Image URLReturns:PIL Image object"""try:response = requests.get(url, timeout=10)response.raise_for_status()image = Image.open(BytesIO(response.content))return image.convert("RGB")except Exception as e:raise ValueError(f"Could not load image from URL: {str(e)}")def validate_image(image: Image.Image) -> bool:"""Validate if the image is suitable for processing.Args:image: PIL Image objectReturns:True if valid, False otherwise"""if image is None:return Falseif image.size[0] <= 0 or image.size[1] <= 0:return Falsereturn Truedef resize_for_processing(image: Image.Image, max_size: int = 1024) -> Image.Image:"""Resize image for processing while maintaining aspect ratio.Args:image: Input PIL Imagemax_size: Maximum size for the longer dimensionReturns:Resized PIL Image"""width, height = image.sizeif max(width, height) <= max_size:return imageif width > height:new_width = max_sizenew_height = int(height * max_size / width)else:new_height = max_sizenew_width = int(width * max_size / height)return image.resize((new_width, new_height), Image.Resampling.LANCZOS)def overlay_masks_advanced(image: Image.Image, masks: torch.Tensor, alpha: float = 0.5) -> Image.Image:"""Advanced overlay function with customizable alpha.Args:image: Input PIL Imagemasks: Segmentation masks tensoralpha: Overlay transparency (0-1)Returns:Overlaid PIL Image"""image = image.convert("RGBA")masks = 255 * masks.cpu().numpy().astype(np.uint8)n_masks = masks.shape[0]if n_masks == 0:return image.convert("RGB")# Use a good colormapcmap = matplotlib.colormaps.get_cmap("tab10").resampled(n_masks)colors = [tuple(int(c * 255) for c in cmap(i)[:3])for i in range(n_masks)]for mask, color in zip(masks, colors):mask_img = Image.fromarray(mask)overlay = Image.new("RGBA", image.size, color + (0,))alpha_map = mask_img.point(lambda v: int(v * alpha * 255))overlay.putalpha(alpha_map)image = Image.alpha_composite(image, overlay)return image207 unmodified lines208209210211207 unmodified lines)if __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860, share=False, debug=True)
app.py+1-106