Spaces:
Sleeping
Sleeping
Update app.py
Browse files207 unmodified lines208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316211207 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 BytesIO
def load_image_from_url(url: str) -> Image.Image: """ Load an image from a URL. Args: url: Image URL Returns: 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 object Returns: True if valid, False otherwise """ if image is None: return False if image.size[0] <= 0 or image.size[1] <= 0: return False return True
def resize_for_processing(image: Image.Image, max_size: int = 1024) -> Image.Image: """ Resize image for processing while maintaining aspect ratio. Args: image: Input PIL Image max_size: Maximum size for the longer dimension Returns: Resized PIL Image """ width, height = image.size if max(width, height) <= max_size: return image if width > height: new_width = max_size new_height = int(height * max_size / width) else: new_height = max_size new_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 Image masks: Segmentation masks tensor alpha: 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 colormap cmap = 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 image demo.launch(server_name="0.0.0.0", server_port=7860, share=False, debug=True)app.py+1-106