Files
novafarma/scripts/clean_single_water.py

57 lines
1.6 KiB
Python

import cv2
import numpy as np
import os
import sys
def remove_white_bg_and_resize(path, target_width=None):
if not os.path.exists(path):
print(f"File not found: {path}")
return
img = cv2.imread(path)
if img is None:
print(f"Error loading {path}")
return
img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
# Threshold for white
gray = cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
_, mask = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
b, g, r, a = cv2.split(img)
final_img = cv2.merge((b, g, r, mask_inv))
# Crop
coords = cv2.findNonZero(mask_inv)
if coords is not None:
x, y, w, h = cv2.boundingRect(coords)
pad = 2
x = max(0, x - pad); y = max(0, y - pad)
w = min(final_img.shape[1] - x, w + 2*pad)
h = min(final_img.shape[0] - y, h + 2*pad)
final_img = final_img[y:y+h, x:x+w]
# Resize
if target_width:
h_curr, w_curr = final_img.shape[:2]
if w_curr > target_width:
ratio = target_width / w_curr
new_h = int(h_curr * ratio)
final_img = cv2.resize(final_img, (target_width, new_h), interpolation=cv2.INTER_AREA)
print(f"Resized {path} to {target_width}x{new_h}")
cv2.imwrite(path, final_img)
print(f"Processed: {path}")
# SAMO NOVA ZADNJA SLIKA
TARGETS = {
'assets/DEMO_FAZA1/Environment/water_clean_patch.png': 512
}
if __name__ == "__main__":
base = os.getcwd()
for rel, w in TARGETS.items():
remove_white_bg_and_resize(os.path.join(base, rel), w)