Skip to content

Instantly share code, notes, and snippets.

@labrax
Created July 18, 2022 19:17
Show Gist options
  • Save labrax/ccc7bd65521137c7f5277fde33e0bfeb to your computer and use it in GitHub Desktop.
Save labrax/ccc7bd65521137c7f5277fde33e0bfeb to your computer and use it in GitHub Desktop.
Convert a file to rgb565 to use with Arduino TFT_eSPI etc
from PIL import Image
import cv2
from glob import glob
def name_to_var(x):
return ''.join([i for i in x if i.isalpha()])
INPUT_FOLDER = './img/raw/'
OUTPUT_FOLDER = './src/img_gen/'
HEADERS = """
// Extracted using Pillow
// Original file: {}
// Original dimensions: {}
// Size in bytes: {}
#if defined(__AVR__)
#include <avr/pgmspace.h>
#elif defined(__PIC32MX__)
#define PROGMEM
#elif defined(__arm__)
#define PROGMEM
#endif
"""
DATA_HEADER = "const unsigned short {}[{}] PROGMEM={{\n\t"
DATA_HEADER_ARRAY = "const unsigned short {}[][{}] PROGMEM={{{{\n\t"
DATA_HEADER_ARRAY_NEXT = "}, {"
DATA_HEADER_CLOSE = "};"
for i in glob(INPUT_FOLDER + '*_profile.png'):
# im = Image.open(i)
im = cv2.imread(i)
im = cv2.cvtColor(im, cv2.COLOR_RGBA2BGR565)
# im = Image.fromarray(im)
newname = name_to_var(i.split('\\')[-1].split('.')[0])
# cv2.imwrite(newname + '.bmp', cv2.cvtColor(im, cv2.COLOR_BGR5652RGBA))
print('Computing', i, newname)
with open(OUTPUT_FOLDER + newname + '.h', 'w') as of:
byte_size = im.size #2 * im._size[0] * im._size[1]
shape = im.shape # im._size
print(HEADERS.format(i, shape, byte_size), end='', file=of)
print(DATA_HEADER.format(newname, byte_size), end='', file=of)
px = 0
height = len(im.tolist()) # im._size[0]
width = len(im.tolist()[0]) # im._size[1]
for i in range(height):
for j in range(width):
b0, b1 = im.tolist()[i][j] # im.getpixel((i, j))
b16el = (b1 << 8) + b0
blue = (b16el >> 11) # 5
green = ((b16el >> 5) & 0b111111) # 6
red = (b16el & 0b11111) # 5
b16el = (red << 11) | (green << 5) | (blue)
print("{0:#06x}".format(b16el), end='', file=of)
more_data = (i < height - 1) or (j < width - 1)
if(more_data):
print(', ', end='', file=of)
px += 1
if(px % 16) == 0:
if more_data:
print('\n\t', end='', file=of)
else:
print('', file=of)
print(DATA_HEADER_CLOSE, file=of)
# DATA_HEADER_ARRAY.format(name, )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment