Created
September 25, 2023 12:34
-
-
Save Guekka/4d6cfa87b05087e4782d8365a59eff14 to your computer and use it in GitHub Desktop.
Quick script using Image Magick to convert an image to a C array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import subprocess | |
from dataclasses import dataclass | |
from typing import List | |
PPM_PATH = "temp.ppm" | |
def to_ppm(png_path: str, resize: str = "") -> str: | |
if os.path.exists(PPM_PATH): | |
os.remove(PPM_PATH) | |
# run convert.exe | |
resize = f"-resize {resize}" if resize else "" | |
subprocess.run( | |
f"convert.exe -compress none {resize} {png_path} {PPM_PATH}", | |
check=True) | |
return PPM_PATH | |
@dataclass | |
class RGB: | |
r: int | |
g: int | |
b: int | |
class PPM: | |
def __init__(self): | |
self.data: List[RGB] = [] | |
self.x = 0 | |
self.y = 0 | |
def parse_ppm(path: str) -> PPM: | |
with open(path, "r") as f: | |
magic = f.readline().strip() | |
if magic != "P3": | |
raise ValueError("Invalid magic") | |
ret = PPM() | |
ret.x, ret.y = map(int, f.readline().strip().split(" ")) | |
color_depth = f.readline().strip() | |
if color_depth != "255": | |
raise ValueError("Invalid color depth") | |
data = iter(f.read().strip().split()) | |
while True: | |
try: | |
r, g, b = map(int, (next(data), next(data), next(data))) | |
ret.data.append(RGB(r, g, b)) | |
except StopIteration: | |
break | |
return ret | |
class PPMBlackWhite: | |
def __init__(self): | |
self.data: List[bool] = [] | |
self.x = 0 | |
self.y = 0 | |
def to_ppm_blackwhite(ppm: PPM) -> PPMBlackWhite: | |
ret = PPMBlackWhite() | |
ret.x = ppm.x | |
ret.y = ppm.y | |
for rgb in ppm.data: | |
ret.data.append(rgb != RGB(255, 255, 255)) | |
return ret | |
def to_c_array(ppmbw: PPMBlackWhite) -> str: | |
ret = f"constexpr bool data[{ppmbw.x * ppmbw.y}]" + "{\n" | |
for i, is_black in enumerate(ppmbw.data): | |
if i != 0 and i % ppmbw.x == 0: | |
ret += "\n" | |
ret += f"{int(is_black)}," | |
ret += "\n};" | |
return ret | |
def main(): | |
to_ppm("test.png", resize="32x32") | |
ppm = parse_ppm(PPM_PATH) | |
ppmbw = to_ppm_blackwhite(ppm) | |
print(to_c_array(ppmbw)) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment