72 lines
2.2 KiB
Python
72 lines
2.2 KiB
Python
import cv2
|
|
import numpy as np
|
|
import os
|
|
|
|
def clean_pipe_stream_aggressive():
|
|
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)
|
|
if img_bgr is None:
|
|
print("Failed to load")
|
|
return
|
|
|
|
# Convert to HSV for better segmentation
|
|
hsv = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2HSV)
|
|
|
|
# The background is a "neutral gray".
|
|
# Gray means LOW Saturation.
|
|
# Light Gray means HIGH Value.
|
|
|
|
# Let's define "Background" as:
|
|
# Saturation < 20 (very gray)
|
|
# Value > 200 (very bright)
|
|
# But wait, the pipe is also gray! We risk deleting the pipe.
|
|
|
|
# Plan B: GrabCut.
|
|
# We initialize a mask where the center is "Probable Foreground" and edges are "Background".
|
|
mask = np.zeros(img_bgr.shape[:2], np.uint8)
|
|
|
|
bgdModel = np.zeros((1,65),np.float64)
|
|
fgdModel = np.zeros((1,65),np.float64)
|
|
|
|
h, w = img_bgr.shape[:2]
|
|
|
|
# Define rectangle: Cut off 10px from edges as "Definite Background"
|
|
# Everything else is "Probable Foreground"
|
|
rect = (10, 10, w-20, h-20)
|
|
|
|
print("Running GrabCut (this might take a second)...")
|
|
cv2.grabCut(img_bgr, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT)
|
|
|
|
# Mask values: 0=BG, 1=FG, 2=Prob BG, 3=Prob FG
|
|
# We take 1 and 3 as mask
|
|
mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
|
|
|
|
img_bgr = img_bgr * mask2[:,:,np.newaxis]
|
|
|
|
# Now create Alpha channel
|
|
b, g, r = cv2.split(img_bgr)
|
|
alpha = mask2 * 255
|
|
img_rgba = cv2.merge([b, g, r, alpha])
|
|
|
|
# Crop to content
|
|
coords = cv2.findNonZero(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_aggressive()
|