import os
from PIL import Image
import numpy as np
from collections import deque

def remove_background(im, threshold=210):
    im = im.convert('RGBA')
    arr = np.array(im)
    h, w, _ = arr.shape
    
    visited = np.zeros((h, w), dtype=bool)
    to_remove = np.zeros((h, w), dtype=bool)
    
    queue = deque()
    
    # Border pixels
    for y in range(h):
        for x in [0, w-1]:
            queue.append((y, x))
            visited[y, x] = True
    for x in range(w):
        for y in [0, h-1]:
            if not visited[y, x]:
                queue.append((y, x))
                visited[y, x] = True
                
    while queue:
        cy, cx = queue.popleft()
        r, g, b, a = arr[cy, cx]
        
        # Check if pixel is background
        is_bg = (a < 64) or (r >= threshold and g >= threshold and b >= threshold)
        
        if is_bg:
            to_remove[cy, cx] = True
            for dy, dx in [(-1,0), (1,0), (0,-1), (0,1)]:
                ny, nx = cy + dy, cx + dx
                if 0 <= ny < h and 0 <= nx < w and not visited[ny, nx]:
                    visited[ny, nx] = True
                    queue.append((ny, nx))
                    
    result = arr.copy()
    result[to_remove, 3] = 0
    return Image.fromarray(result)

folder = r'C:\fuentes\proyectos delphi\ICONOS\raul\iconos'
test_names = ['Cliente.png', 'Clientes.png', 'Pedido de Venta.png', 'Factura de Venta.png', 'Presupuestos Formales.png']
for name in test_names:
    p = os.path.join(folder, name)
    im = Image.open(p)
    clean = remove_background(im)
    arr_orig = np.array(im.convert('RGBA'))
    arr_clean = np.array(clean)
    opaque_orig = int(np.sum(arr_orig[:, :, 3] > 128))
    opaque_clean = int(np.sum(arr_clean[:, :, 3] > 128))
    total = arr_clean.shape[0] * arr_clean.shape[1]
    print(f'{name}: opaque {opaque_orig} -> {opaque_clean} (total {total})')
