from PIL import Image
import numpy
def get_rgb565_bytes_from_image(filename):
rgb888 = numpy.asarray(Image.open(filename))
# check that image have 3 color components, each of 8 bits
assert rgb888.shape[-1] == 3 and rgb888.dtype == numpy.uint8
r5 = (rgb888[..., 0] >> 3 & 0x1f).astype(numpy.uint16)
g6 = (rgb888[..., 1] >> 2 & 0x3f).astype(numpy.uint16)
b5 = (rgb888[..., 2] >> 3 & 0x1f).astype(numpy.uint16)
rgb565 = r5 << 11 | g6 << 5 | b5
return rgb565.tobytes()