73 lines
1.9 KiB
Python
73 lines
1.9 KiB
Python
"""Knock a flat charcoal field out of generated renders so they can be sprites."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from PIL import Image
|
|
|
|
|
|
def sample_background(image: Image.Image) -> tuple[float, float, float]:
|
|
pixels = image.load()
|
|
width, height = image.size
|
|
samples: list[tuple[int, int, int]] = []
|
|
for x, y in (
|
|
(2, 2),
|
|
(width - 3, 2),
|
|
(2, height - 3),
|
|
(width - 3, height - 3),
|
|
(width // 2, 2),
|
|
(width // 2, height - 3),
|
|
):
|
|
pixel = pixels[x, y]
|
|
samples.append((pixel[0], pixel[1], pixel[2]))
|
|
count = float(len(samples))
|
|
return (
|
|
sum(sample[0] for sample in samples) / count,
|
|
sum(sample[1] for sample in samples) / count,
|
|
sum(sample[2] for sample in samples) / count,
|
|
)
|
|
|
|
|
|
def punch(path: Path) -> None:
|
|
image = Image.open(path).convert("RGBA")
|
|
background = sample_background(image)
|
|
pixels = image.load()
|
|
width, height = image.size
|
|
for y in range(height):
|
|
for x in range(width):
|
|
red, green, blue, _alpha = pixels[x, y]
|
|
distance = (
|
|
(red - background[0]) ** 2
|
|
+ (green - background[1]) ** 2
|
|
+ (blue - background[2]) ** 2
|
|
) ** 0.5
|
|
if distance < 18:
|
|
alpha = 0
|
|
elif distance < 34:
|
|
alpha = int((distance - 18) * (255.0 / 16.0))
|
|
else:
|
|
alpha = 255
|
|
pixels[x, y] = (red, green, blue, alpha)
|
|
image.save(path)
|
|
|
|
|
|
def main() -> int:
|
|
roots = [
|
|
Path("assets/generated/renders/machines"),
|
|
Path("assets/generated/renders/logistics"),
|
|
Path("assets/generated/renders/items"),
|
|
]
|
|
count = 0
|
|
for root in roots:
|
|
for path in sorted(root.glob("*.png")):
|
|
punch(path)
|
|
count += 1
|
|
print("PUNCHED %d" % count)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|