Badger2040: Add binary support to image converter.
# 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
-import argparse, sys, os, glob
+import argparse
+import sys
from PIL import Image, ImageEnhance
from pathlib import Path
-parser = argparse.ArgumentParser(
- description='Converts images into the format used by Badger2040.')
+parser = argparse.ArgumentParser(description='Converts images into the format used by Badger2040.')
parser.add_argument('file', nargs="+", help='input files to convert')
+parser.add_argument('--binary', action="store_true", help='output binary file for MicroPython')
-options = None
-try:
options = parser.parse_args()
-except:
- parser.print_help()
- sys.exit(0)
+
def convert_image(img):
- img = img.resize((296, 128)) # resize and crop
+ # img = img.resize((296, 128)) # resize and crop
enhancer = ImageEnhance.Contrast(img)
img = enhancer.enhance(2.0)
img = img.convert("1") # convert to black and white
@@ -35,29 +32,21 @@ for input_filename in options.file:
image_name = Path(input_filename).stem
- h, w = img.size
-
- data = Image.Image.getdata(img)
-
- bytes = []
- byte = 0
- byte_idx = 0
- x = 0
- for v in data:
- byte <<= 1
- byte |= 1 if v == 0 else 0
- byte_idx += 1
+ w, h = img.size
- if byte_idx == 8: # next byte...
- bytes.append(str(byte))
- byte_idx = 0
- byte = 0
+ output_data = [~b & 0xff for b in list(img.tobytes())]
+ if options.binary:
+ output_filename = input_filename + ".bin"
+ print(f"Saving to {output_filename}")
+ with open(output_filename, "wb") as out:
+ out.write(bytearray(output_data))
+ else:
image_code = '''\
static const uint8_t {image_name}[{count}] = {{
{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)
