Badger2040: Add binary support to image converter.

pull/252/head
Phil Howard 2022-02-24 09:23:52 +00:00
rodzic 74d004b939
commit 2e741c7993
1 zmienionych plików z 26 dodań i 37 usunięć

Wyświetl plik

@ -5,60 +5,49 @@
# and reducing to black and white with dither. the data is then output as an # and reducing to black and white with dither. the data is then output as an
# array that can be embedded directly into your c++ code # array that can be embedded directly into your c++ code
import argparse, sys, os, glob import argparse
import sys
from PIL import Image, ImageEnhance from PIL import Image, ImageEnhance
from pathlib import Path from pathlib import Path
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(description='Converts images into the format used by Badger2040.')
description='Converts images into the format used by Badger2040.')
parser.add_argument('file', nargs="+", help='input files to convert') parser.add_argument('file', nargs="+", help='input files to convert')
parser.add_argument('--binary', action="store_true", help='output binary file for MicroPython')
options = parser.parse_args()
options = None
try:
options = parser.parse_args()
except:
parser.print_help()
sys.exit(0)
def convert_image(img): def convert_image(img):
img = img.resize((296, 128)) # resize and crop # img = img.resize((296, 128)) # resize and crop
enhancer = ImageEnhance.Contrast(img) enhancer = ImageEnhance.Contrast(img)
img = enhancer.enhance(2.0) img = enhancer.enhance(2.0)
img = img.convert("1") # convert to black and white img = img.convert("1") # convert to black and white
return img return img
# create map of images based on input filenames # create map of images based on input filenames
for input_filename in options.file: for input_filename in options.file:
with Image.open(input_filename) as img: with Image.open(input_filename) as img:
img = convert_image(img) img = convert_image(img)
image_name = Path(input_filename).stem image_name = Path(input_filename).stem
h, w = img.size w, h = img.size
data = Image.Image.getdata(img) output_data = [~b & 0xff for b in list(img.tobytes())]
bytes = [] if options.binary:
byte = 0 output_filename = input_filename + ".bin"
byte_idx = 0 print(f"Saving to {output_filename}")
x = 0 with open(output_filename, "wb") as out:
for v in data: out.write(bytearray(output_data))
byte <<= 1 else:
byte |= 1 if v == 0 else 0 image_code = '''\
byte_idx += 1
if byte_idx == 8: # next byte...
bytes.append(str(byte))
byte_idx = 0
byte = 0
image_code = '''\
static const uint8_t {image_name}[{count}] = {{ static const uint8_t {image_name}[{count}] = {{
{byte_data} {byte_data}
}}; }};
'''.format(image_name=image_name, count=len(bytes), byte_data=", ".join(bytes)) '''.format(image_name=image_name, count=len(output_data), byte_data=", ".join(str(b) for b in output_data))
print(image_code) print(image_code)