You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

49 lines
1.3 KiB

#!/usr/bin/env python3
import argparse
import json
from pathlib import Path
from PIL import Image
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Convert an image file into a JSON matrix of RGBA pixels."
)
parser.add_argument("input_image", type=Path, help="Source image path")
parser.add_argument("output_json", type=Path, help="Destination JSON path")
return parser.parse_args()
def image_to_matrix(image_path: Path) -> dict:
with Image.open(image_path) as image:
rgba_image = image.convert("RGBA")
width, height = rgba_image.size
pixel_map = rgba_image.load()
rows = [
[list(pixel_map[x, y]) for x in range(width)]
for y in range(height)
]
return {
"source": image_path.name,
"width": width,
"height": height,
"mode": "RGBA",
"pixels": rows,
}
def main() -> None:
args = parse_args()
data = image_to_matrix(args.input_image)
args.output_json.parent.mkdir(parents=True, exist_ok=True)
args.output_json.write_text(json.dumps(data, indent=2), encoding="utf-8")
print(
f"Wrote {args.output_json} with {data['width']}x{data['height']} RGBA pixels"
)
if __name__ == "__main__":
main()