N
N
Nikolay Neupokoev2016-03-03 20:24:15
Python
Nikolay Neupokoev, 2016-03-03 20:24:15

How to convert image to bmp565 format in Python?

Given:

  • Picture. Without loss of generality, we will assume that it is in 24-bit bmp format - this can be exactly set in Paint. Less than 256 colors only
  • Python 3 (Version 3 due to bytearray )
  • Pillow (fork PIL)
  • Method that gives a representation of the picture as bytes
What you need: get a bytearray, where each pixel is encoded using 2 bytes (in bmp565 format)
rgb565.gif
I think it's enough to find a solution for at least one point:
  • graphics editor that saves in rgb565
  • function to convert images byte by byte from any format to rgb565
  • a way to convert using Pillow to rgb565 or another library capable of this

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nirvimel, 2016-03-04
@stakanmartini

My version:

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()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question