import numpy as np, cv2, sys
from PIL import Image
src = sys.argv[1]
img = np.array(Image.open(src).convert('RGB')).astype(int)
h, w = img.shape[:2]
white = (img.min(axis=2) > 225)
# bg = white connected to border
n, lab = cv2.connectedComponents(white.astype(np.uint8), connectivity=4)
border = set(np.unique(np.concatenate([lab[0], lab[-1], lab[:, 0], lab[:, -1]])))
bg = np.isin(lab, [b for b in border if b != 0] + [])
bg &= white
fg = ~bg
fg = cv2.morphologyEx(fg.astype(np.uint8), cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
n, lab, st, cen = cv2.connectedComponentsWithStats(fg, connectivity=8)
for i in range(1, n):
    x, y, ww, hh, a = st[i]
    if a > 2000: print(i, x, y, ww, hh, a)
np.save(src + '.lab.npy', lab)
