Skip to content

Instantly share code, notes, and snippets.

@Enchan1207
Last active February 10, 2024 07:12
Show Gist options
  • Save Enchan1207/f0212f9ea90507fd9e9ab04ce6cfaa50 to your computer and use it in GitHub Desktop.
Save Enchan1207/f0212f9ea90507fd9e9ab04ce6cfaa50 to your computer and use it in GitHub Desktop.
2値画像をグラフィック液晶に反映可能な形式に変換する
#
#
#
import sys
from typing import List
import numpy as np
from PIL import Image
file_path = "/path/to/image.png"
def main() -> int:
# 読み込んでnp配列に変換
print("Load image...")
image = np.array(Image.open(file_path))
print(f"path: {file_path}\nsize: {image.shape}")
# バイナリデータに変換
print("Convert to binary...")
image_data: List[bytes] = []
for n_row in range(0, image.shape[1], 8):
# 画像を縦8pxずつ分割
image_part = image[n_row : n_row + 8]
# 各行について 2^行 を乗じる (0行目は0/1、7行目は0/128となる)
for n in range(8):
image_part[n] *= 2**n
# 縦に足す これにより縦方向のピクセル情報が00~FFに変換される
image_part_compressed = 0xFF - np.sum(image_part, axis=0, dtype=np.uint8)
image_data.append(image_part_compressed.tobytes())
# ビジュアライズ
for x in range(8):
for y in range(48):
print("@@" if image_part[x][y] else " ", end="")
print()
for c in image_part_compressed:
print(f"{c:02X}", end="")
print("\n")
# バイナリからCのソースを出力する
print("Export image data to file...")
with open("image.c", "w") as dest:
dest.write(f"const uint8_t image[{len(image_data)}][{len(image_data[0])}] = {{\n")
image_data_str = [", ".join([f"0x{n:02X}" for n in line]) for line in image_data]
for line in image_data_str:
dest.write(f" {{{line}}},\n")
dest.write("};\n")
return 0
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment