import numpy as np from PIL import Image, ImageFilter from collections import deque import os def remove_background(im_path, out_path, tol=33): im = Image.open(im_path).convert('RGBA') w, h = im.size arr = np.array(im) rgb = arr[:, :, :3].astype(np.float32) # 取邊緣像素做背景色基準 border_pixels = np.concatenate([ rgb[0:4, :, :].reshape(-1, 3), rgb[h-4:h, :, :].reshape(-1, 3), rgb[:, 0:4, :].reshape(-1, 3), rgb[:, w-4:w, :].reshape(-1, 3) ], axis=0) bg_color = np.median(border_pixels, axis=0) # 計算各像素與背景色的歐氏距離 dist = np.linalg.norm(rgb - bg_color, axis=2) # 邊界 BFS 蔓延遮罩 bg_mask = np.zeros((h, w), dtype=bool) visited = np.zeros((h, w), dtype=bool) queue = deque() for x in range(w): if dist[0, x] < tol: queue.append((0, x)); visited[0, x] = True if dist[h-1, x] < tol: queue.append((h-1, x)); visited[h-1, x] = True for y in range(h): if dist[y, 0] < tol and not visited[y, 0]: queue.append((y, 0)); visited[y, 0] = True if dist[y, w-1] < tol and not visited[y, w-1]: queue.append((y, w-1)); visited[y, w-1] = True while queue: cy, cx = queue.popleft() bg_mask[cy, cx] = True for ny, nx in ((cy-1, cx), (cy+1, cx), (cy, cx-1), (cy, cx+1)): if 0 <= ny < h and 0 <= nx < w and not visited[ny, nx]: visited[ny, nx] = True if dist[ny, nx] < tol: queue.append((ny, nx)) # 前景遮罩 = 非背景 (0=透明, 255=實體) fg_mask = (~bg_mask).astype(np.uint8) * 255 alpha_img = Image.fromarray(fg_mask, mode='L') # 形態學過濾:MinFilter 消除孤立小顆粒/星芒殘留 alpha_clean = alpha_img.filter(ImageFilter.MinFilter(5)) alpha_clean = alpha_clean.filter(ImageFilter.MaxFilter(5)) # 邊緣羽化平滑 alpha_smooth = alpha_clean.filter(ImageFilter.GaussianBlur(radius=1.2)) arr[:, :, 3] = np.array(alpha_smooth) res = Image.fromarray(arr, mode='RGBA') res.save(out_path, 'PNG') print(f'Cutout done: {out_path}') if __name__ == '__main__': for i in range(1, 9): src = f'assets/building_b{i}.jpg' dst = f'assets/building_b{i}.png' if os.path.exists(src): remove_background(src, dst)