The open imaging DSP library
Loading...
Searching...
No Matches
How to palettize images

Convert images from RGB to indexed color mode.

The palettize and depalettize operations bring the ability to reduce the number of colors in the image down to a compact palette.

First the image is imported from a buffer or another source.

struct mpix_image img;
mpix_image_from_buf(&img, buf, sizeof(buf), 640, 480, MPIX_FMT_RGB24);
#define MPIX_FMT_RGB24
Definition formats.h:125
static void mpix_image_from_buf(struct mpix_image *img, const uint8_t *buffer, size_t size, const struct mpix_format *fmt)
Initialize an image from a memory buffer.
Definition image.h:30
Represent the image currently being processed.
Definition types.h:136

The palette need to be allocated. In some cases, stack space will be too small for the palette buffer and need to be made a global array variable.

Here 3 is for 3 byte per pixel (RGB24) and 4 is because of the PALETTE4 format is selected.

uint8_t colors[3 << 4]
struct mpix_palette palette = {.colors = colors, fourcc = MPIX_FMT_PALETTE4};
#define MPIX_FMT_PALETTE4
Definition formats.h:459
Definition types.h:160
uint32_t fourcc
Definition types.h:164

Then the color palette can be generated from the content of the image. The number 1000 refers to the number of pixels sampled from the image used to generate the palette.

The algorithm used is k-mean. It can be run multiple times to run multiple k-mean cycles and improve the palette to better match the image. However, the palette can remain the same across several frames and in such case, a single call can be done per frame to continuously adjusting the color palette to the new frames.

mpix_image_optimize_palette(img, &palette, 2000);
int mpix_image_optimize_palette(struct mpix_image *img, struct mpix_palette *palette, uint16_t num_samples)
Optimize a color palette after the values from the image.

Now that a palette is generated, it is possible to use it to encode the input image:

static int mpix_image_palette_encode(struct mpix_image *img, uint32_t fourcc)
Convert an image to an indexed color format.
Definition image.h:83

For getting RGB data back, it is possible to run the opposite operation with the same palette:

static int mpix_image_palette_decode(struct mpix_image *img)
Convert an image from an indexed color format.
Definition image.h:98

See Supported operations for the list of all palettization format. The conversion is always between RGB24 and one of the palette size.