ingest.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/env python3
  2. from PIL import Image
  3. def ingest_png(file_name: str) -> tuple[str, int, int, int, int]:
  4. print(f"Ingesting {file_name}")
  5. # image name - strip leading path and trailing extension
  6. name = file_name.rsplit("/", maxsplit=1)[1].split(".", maxsplit=1)[0]
  7. # read non-transparent pixels of image as RGB values
  8. 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)]
  9. # X metric - mean sq norm of all pixels
  10. x = sum(x * x + y * y + z * z for x, y, z in pixels) / len(pixels)
  11. # Y metrics - mean of color components
  12. yr_sum = 0
  13. yg_sum = 0
  14. yb_sum = 0
  15. for r, g, b in pixels:
  16. yr_sum += r
  17. yg_sum += g
  18. yb_sum += b
  19. yr = yr_sum / len(pixels)
  20. yg = yg_sum / len(pixels)
  21. yb = yb_sum / len(pixels)
  22. return name, x, yr, yg, yb
  23. if __name__ == "__main__":
  24. import csv
  25. import os
  26. data = [ingest_png("pngs/" + fn) for f in os.listdir("pngs") if (fn := os.fsdecode(f)).endswith(".png")]
  27. with open("database.csv", "w") as outfile:
  28. writer = csv.writer(outfile, delimiter=",", quotechar="'")
  29. writer.writerows(data)
  30. with open("database.js", "w") as outfile:
  31. outfile.write("const database = [\n")
  32. for name, x, yr, yg, yb in data:
  33. outfile.write(f' [ "{name}", {x}, {yr}, {yg}, {yb} ],\n')
  34. outfile.write("];\n")