12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- #!/usr/bin/env python3
- from collections import namedtuple
- import numpy as np
- from PIL import Image
- from colorspacious import cspace_convert
- def is_outline(r: int, g: int, b: int, a: int) -> bool:
- # returns true if a pixel is transparent or pure black
- return a == 0 or (r, g, b) == (0, 0, 0)
- def x_metric(pixels: np.array) -> float:
- # X metric - the mean squared Euclidean norm
- # computed as the sum of the squares of the components of the pixels,
- # normalized by the number of pixels
- return sum(sum(pixels ** 2)) / len(pixels)
- def y_metric(pixels: np.array) -> np.array:
- # Y metric - the mean pixel of the image
- return sum(pixels) / len(pixels)
- ImageInfo = namedtuple(
- "ImageInfo", ["name", "xrgb", "xjab", "yrgb", "yjab"]
- )
- def ingest_png(file_name: str) -> ImageInfo:
- 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-outline pixels of image
- rgb_pixels = np.array([
- (r, g, b)
- for r, g, b, a in Image.open(file_name).convert("RGBA").getdata()
- if not is_outline(r, g, b, a)
- ])
- # convert RGB pixels to CAM02 values
- jab_pixels = cspace_convert(rgb_pixels, "sRGB255", "CAM02-UCS")
- # compute and return metrics
- return ImageInfo(
- name=name,
- xrgb=x_metric(rgb_pixels),
- xjab=x_metric(jab_pixels),
- yrgb=y_metric(rgb_pixels),
- yjab=y_metric(jab_pixels),
- )
- if __name__ == "__main__":
- import csv
- import os
- import sys
- dir = "pngs" if len(sys.argv) < 2 else sys.argv[1]
- data = [
- ingest_png(dir + "/" + fn)
- for f in os.listdir(dir)
- if (fn := os.fsdecode(f)).endswith(".png")
- ]
- with open("database.csv", "w") as outfile:
- writer = csv.writer(outfile, delimiter=",", quotechar="'")
- writer.writerows([d.name, d.xrgb, *d.yrgb] for d in data)
- with open("database-cam02.csv", "w") as outfile:
- writer = csv.writer(outfile, delimiter=",", quotechar="'")
- writer.writerows([d.name, d.xjab, *d.yjab] for d in data)
- with open("database.js", "w") as outfile:
- outfile.write("const database = [\n")
- for info in data:
- fields = ", ".join(
- (
- f'name: "{info.name}"',
- f"xRGB: {info.xrgb}",
- f"xJAB: {info.xjab}",
- f"yRGB: [ {', '.join(str(c) for c in info.yrgb)} ]",
- f"yJAB: [ {', '.join(str(c) for c in info.yjab)} ]",
- )
- )
- outfile.write(f" {{ {fields} }},\n")
- outfile.write("];\n")
|