34 lines
1.0 KiB
Python
34 lines
1.0 KiB
Python
|
|
#!/usr/bin/env python3
|
||
|
|
# to_1ch_white_bg.py
|
||
|
|
from PIL import Image
|
||
|
|
import sys
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
|
||
|
|
def to_1ch_white_bg(in_path: str, out_path: str | None = None) -> str:
|
||
|
|
im = Image.open(in_path)
|
||
|
|
|
||
|
|
# Если есть альфа — композитим на белый
|
||
|
|
if im.mode in ("RGBA", "LA") or ("transparency" in im.info):
|
||
|
|
im = im.convert("RGBA")
|
||
|
|
white = Image.new("RGBA", im.size, (255, 255, 255, 255))
|
||
|
|
im = Image.alpha_composite(white, im).convert("RGB")
|
||
|
|
else:
|
||
|
|
im = im.convert("RGB")
|
||
|
|
|
||
|
|
gray = im.convert("L") # 1 канал
|
||
|
|
if out_path is None:
|
||
|
|
p = Path(in_path)
|
||
|
|
out_path = str(p.with_name(f"{p.stem}_1ch.png"))
|
||
|
|
gray.save(out_path, format="PNG", optimize=True)
|
||
|
|
return out_path
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
if len(sys.argv) < 2:
|
||
|
|
print(
|
||
|
|
"Использование: python to_1ch_white_bg.py input.png [output.png]")
|
||
|
|
sys.exit(1)
|
||
|
|
print(to_1ch_white_bg(sys.argv[1],
|
||
|
|
sys.argv[2] if len(sys.argv) > 2 else None))
|