50 lines
1.3 KiB
Python
50 lines
1.3 KiB
Python
import sys
|
|
from collections import deque
|
|
from pathlib import Path
|
|
|
|
from PIL import Image
|
|
|
|
|
|
def color_dist(c1: tuple[int, int, int], c2: tuple[int, int, int]) -> float:
|
|
return sum((a - b) ** 2 for a, b in zip(c1, c2)) ** 0.5
|
|
|
|
|
|
def remove_background(input_path: Path, output_path: Path, tolerance: float = 42) -> None:
|
|
img = Image.open(input_path).convert('RGBA')
|
|
pixels = img.load()
|
|
width, height = img.size
|
|
|
|
seeds = [
|
|
(0, 0),
|
|
(width - 1, 0),
|
|
(0, height - 1),
|
|
(width - 1, height - 1),
|
|
(width // 2, 0),
|
|
(width // 2, height - 1),
|
|
]
|
|
bg_colors = [pixels[x, y][:3] for x, y in seeds]
|
|
|
|
visited: set[tuple[int, int]] = set()
|
|
queue: deque[tuple[int, int]] = deque(seeds)
|
|
|
|
while queue:
|
|
x, y = queue.popleft()
|
|
if (x, y) in visited or x < 0 or y < 0 or x >= width or y >= height:
|
|
continue
|
|
|
|
visited.add((x, y))
|
|
current = pixels[x, y][:3]
|
|
|
|
if not any(color_dist(current, bg) <= tolerance for bg in bg_colors):
|
|
continue
|
|
|
|
pixels[x, y] = (current[0], current[1], current[2], 0)
|
|
queue.extend([(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)])
|
|
|
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
img.save(output_path, 'PNG')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
remove_background(Path(sys.argv[1]), Path(sys.argv[2]))
|