ingest.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/env python3
  2. from collections import namedtuple
  3. from PIL import Image
  4. from convert import rgb_to_cieluv
  5. def is_outline(r: int, g: int, b: int, a: int) -> bool:
  6. # returns true if a pixel is transparent or pure black
  7. return a == 0 or (r, g, b) == (0, 0, 0)
  8. def x_metric(pixels: list[tuple[float, float, float]]) -> float:
  9. # X metric - the mean squared Euclidean norm
  10. # computed as the sum of the squares of the components of the pixels,
  11. # normalized by the number of pixels
  12. return sum(comp * comp for pix in pixels for comp in pix) / len(pixels)
  13. def y_metric(pixels: list[tuple[float, float, float]]) -> tuple[float, float, float]:
  14. # Y metric - the mean pixel of the image
  15. return tuple(sum(p[i] for p in pixels) / len(pixels) for i in range(3))
  16. ImageInfo = namedtuple("ImageInfo", ["name", "xrgb", "xluv", "yr", "yg", "yb", "yl", "yu", "yv"])
  17. def ingest_png(file_name: str) -> ImageInfo:
  18. print(f"Ingesting {file_name}")
  19. # image name - strip leading path and trailing extension
  20. name = file_name.rsplit("/", maxsplit=1)[1].split(".", maxsplit=1)[0]
  21. # read non-outline pixels of image
  22. rgb_pixels = [(r, g, b)
  23. for r, g, b, a in Image.open(file_name).convert("RGBA").getdata()
  24. if not is_outline(r, g, b, a)]
  25. # convert RGB pixels to CIELUV values
  26. luv_pixels = [rgb_to_cieluv(*p) for p in rgb_pixels]
  27. # compute and return metrics
  28. xrgb = x_metric(rgb_pixels)
  29. xluv = x_metric(luv_pixels)
  30. yr, yg, yb = y_metric(rgb_pixels)
  31. yl, yu, yv = y_metric(luv_pixels)
  32. return ImageInfo(
  33. name=name,
  34. xrgb=xrgb,
  35. xluv=xluv,
  36. yr=yr,
  37. yg=yg,
  38. yb=yb,
  39. yl=yl,
  40. yu=yu,
  41. yv=yv,
  42. )
  43. if __name__ == "__main__":
  44. import csv
  45. import os
  46. data = [ingest_png("pngs/" + fn) for f in os.listdir("pngs") if (fn := os.fsdecode(f)).endswith(".png")]
  47. with open("database.csv", "w") as outfile:
  48. writer = csv.writer(outfile, delimiter=",", quotechar="'")
  49. writer.writerows([d.name, d.xrgb, d.yr, d.yg, d.yb] for d in data)
  50. with open("database-luv.csv", "w") as outfile:
  51. writer = csv.writer(outfile, delimiter=",", quotechar="'")
  52. writer.writerows([d.name, d.xluv, d.yl, d.yu, d.yv] for d in data)
  53. with open("database.js", "w") as outfile:
  54. outfile.write("const database = [\n")
  55. for info in data:
  56. fields = ", ".join((
  57. f'name: "{info.name}"',
  58. f"xRGB: {info.xrgb}",
  59. f"xLUV: {info.xluv}",
  60. f"yRGB: [ {info.yr}, {info.yg}, {info.yb} ]",
  61. f"yLUV: [ {info.yl}, {info.yu}, {info.yv} ]",
  62. ))
  63. outfile.write(f" {{ {fields} }},\n")
  64. outfile.write("];\n")