pimoroni-pico/examples/badger2040/image_converter/convert.py

54 lines
1.7 KiB
Python
Raw Normal View History

2022-01-27 13:07:58 +00:00
#!/usr/bin/env python3
# converts images into a format suitable for display on badger2040. this
# includes scaling the image fit the longest edge, cropping down to 296x128
# 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
import sys
2022-01-27 13:07:58 +00:00
from PIL import Image, ImageEnhance
from pathlib import Path
parser = argparse.ArgumentParser(description='Converts images into the format used by Badger2040.')
2022-01-27 13:07:58 +00:00
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()
2022-01-27 13:07:58 +00:00
def convert_image(img):
# 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
return img
2022-01-27 13:07:58 +00:00
# create map of images based on input filenames
for input_filename in options.file:
with Image.open(input_filename) as img:
img = convert_image(img)
2022-01-27 13:07:58 +00:00
image_name = Path(input_filename).stem
2022-01-27 13:07:58 +00:00
w, h = img.size
2022-01-27 13:07:58 +00:00
output_data = [~b & 0xff for b in list(img.tobytes())]
2022-01-27 13:07:58 +00:00
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 = '''\
2022-01-27 13:07:58 +00:00
static const uint8_t {image_name}[{count}] = {{
{byte_data}
2022-01-27 13:07:58 +00:00
}};
'''.format(image_name=image_name, count=len(output_data), byte_data=", ".join(str(b) for b in output_data))
2022-01-27 13:07:58 +00:00
print(image_code)
2022-01-27 13:07:58 +00:00