import cv2 import numpy as np import os def clean_pipe_stream_v2(): src_path = '/Users/davidkotnik/.gemini/antigravity/brain/07019d04-a214-43ab-9565-86f4e8f17e5b/uploaded_media_1769607894587.jpg' print(f"Loading {src_path}") img_bgr = cv2.imread(src_path) # Load as BGR (3 channels) first for floodFill if img_bgr is None: print("Failed") return # Create mask for floodFill (h+2, w+2) h, w = img_bgr.shape[:2] mask = np.zeros((h+2, w+2), np.uint8) # Flags: Fixed range, result in mask, fill with something (doesn't matter for mask-only) # The mask will be updated with 1s where filled. flood_flags = 4 | (255 << 8) | cv2.FLOODFILL_MASK_ONLY | cv2.FLOODFILL_FIXED_RANGE # Seed points (Corners) # Tolerance: +/- 15 lo_diff = (15, 15, 15) up_diff = (15, 15, 15) cv2.floodFill(img_bgr, mask, (0,0), 0, lo_diff, up_diff, flood_flags) cv2.floodFill(img_bgr, mask, (w-1,0), 0, lo_diff, up_diff, flood_flags) cv2.floodFill(img_bgr, mask, (0,h-1), 0, lo_diff, up_diff, flood_flags) # Extract the mask corresponding to the image (remove border) # The mask has 255 where BG was found. alpha_mask = mask[1:-1, 1:-1] # Invert mask: We want 255 (Opaque) where it is NOT background (0 in mask) # Background (255 in mask) -> Should be 0 (Transparent) # Foreground (0 in mask) -> Should be 255 (Opaque) final_alpha = cv2.bitwise_not(alpha_mask) # Create valid RGBA image b, g, r = cv2.split(img_bgr) img_rgba = cv2.merge([b, g, r, final_alpha]) # Crop coords = cv2.findNonZero(final_alpha) if coords is not None: x, y, cw, ch = cv2.boundingRect(coords) print(f"Cropping to: {x},{y} {cw}x{ch}") img_rgba = img_rgba[y:y+ch, x:x+cw] # Save targets = [ '/Users/davidkotnik/repos/novafarma/main/assets/stream_pipe.png', '/Users/davidkotnik/repos/novafarma/assets/DEMO_FAZA1/Environment/stream_pipe.png' ] for t in targets: cv2.imwrite(t, img_rgba) print(f"Saved to {t}") if __name__ == "__main__": clean_pipe_stream_v2()