123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- #!/usr/bin/env python3
- from PIL import Image
- def ingest_png(file_name: str) -> tuple[str, int, int, int, int]:
- print(f"Ingesting {file_name}")
- # image name - strip leading path and trailing extension
- name = file_name.rsplit("/", maxsplit=1)[1].split(".", maxsplit=1)[0]
- # read non-transparent pixels of image as RGB values
- pixels = [(r, g, b) for r, g, b, a in Image.open(file_name).convert("RGBA").getdata() if a > 0 and (r > 0 or g > 0 or b > 0)]
- # X metric - mean sq norm of all pixels
- x = sum(x * x + y * y + z * z for x, y, z in pixels) / len(pixels)
- # Y metrics - mean of color components
- yr_sum = 0
- yg_sum = 0
- yb_sum = 0
- for r, g, b in pixels:
- yr_sum += r
- yg_sum += g
- yb_sum += b
- yr = yr_sum / len(pixels)
- yg = yg_sum / len(pixels)
- yb = yb_sum / len(pixels)
- return name, x, yr, yg, yb
- if __name__ == "__main__":
- import csv
- import os
- data = [ingest_png("pngs/" + fn) for f in os.listdir("pngs") if (fn := os.fsdecode(f)).endswith(".png")]
- with open("database.csv", "w") as outfile:
- writer = csv.writer(outfile, delimiter=",", quotechar="'")
- writer.writerows(data)
- with open("database.js", "w") as outfile:
- outfile.write("const database = [\n")
- for name, x, yr, yg, yb in data:
- outfile.write(f' [ "{name}", {x}, {yr}, {yg}, {yb} ],\n')
- outfile.write("];\n")
|