23

I’ve got my hands on a 16-bit rgb565 image (specifically, an Android framebuffer dump), and I would like to convert it to 24-bit rgb888 for viewing on a normal monitor.

The question is, how does one convert a 5- or 6-bit channel to 8 bits? The obvious answer is to shift it. I started out by writing this:

puts("P6 320 480 255");
uint16_t buf;
while (read(0, &buf, sizeof buf)) {
    unsigned char red = (buf & 0xf800) >> 11;
    unsigned char green = (buf & 0x07e0) >> 5;
    unsigned char blue = buf & 0x001f;
    putchar(red << 3);
    putchar(green << 2);
    putchar(blue << 3);
}

However, this doesn’t have one property I would like, which is for 0xffff to map to 0xffffff, instead of 0xf8fcf8. I need to expand the value in some way, but I’m not sure how that should work.

The Android SDK comes with a tool called ddms (Dalvik Debug Monitor) that takes screen captures. As far as I can tell from reading the code, it implements the same logic; yet its screenshots are coming out different, and white is mapping to white.

Here’s the raw framebuffer, the smart conversion by ddms, and the dumb conversion by the above algorithm. Note that the latter is slightly darker and greener.

(By the way, this conversion is implemented in ffmpeg, but it’s just performing the dumb conversion listed above, leaving the LSBs at all zero.)

I guess I have two questions:

  • What’s the most sensible way to convert rgb565 to rgb888?
  • How is DDMS converting its screenshots?

10 Answers 10

25

My few cents:

If you care about precise mapping, yet fast algorithm you can consider this:

R8 = ( R5 * 527 + 23 ) >> 6;
G8 = ( G6 * 259 + 33 ) >> 6;
B8 = ( B5 * 527 + 23 ) >> 6;

It uses only: MUL, ADD and SHR -> so it is pretty fast! From the other side it is compatible in 100% to floating point mapping with proper rounding:

// R8 = (int) floor( R5 * 255.0 / 31.0 + 0.5);
// G8 = (int) floor( G6 * 255.0 / 63.0 + 0.5);
// B8 = (int) floor( R5 * 255.0 / 31.0 + 0.5);

Some extra cents: If you are interested in 888 to 565 conversion, this works very well too:

R5 = ( R8 * 249 + 1014 ) >> 11;
G6 = ( G8 * 253 +  505 ) >> 10;
B5 = ( B8 * 249 + 1014 ) >> 11;

Constants were found using brute force search with somę early rejections to speed thing up a bit.

4
  • 6
    How did you calculate these values? (I'd like to use the same trick for other channel depths.) Apr 5, 2013 at 13:52
  • 2
    To be pedantic, floor(x+0.5) is not the same thing as round(x), and you actually want the latter. floor(x+0.5) does the wrong thing for 0.5f-1ulp, which it rounds up. 0.5f-1ulp doesn't happen here. You can calculate values like this by starting with the right shift you intend to do at the end (e.g. /64 in this case) and multiply through the scale factor (255/31) by it. You get 255*64/31 = 526.45. It is an approximation. Luckily there are not many numbers for which this has to work. So, you can often get exactly the right result if you are close enough. Mar 30, 2015 at 17:18
  • 1
    I've down-voted this because there is no explanation for why these values are chosen. Even if you have a basic understanding of fixed point arithmetic it doesn't seem obvious why it was implemented this way. If a fixed point integer with 6 fractional digits was chosen, then the multiplier 527 seems to be incorrectly rounded. And how do 23 and 33 correspond to 0.5? Why is it different for green? It seems it should just be 32. I don't think it is prudent to spread these unintuitive secret sauce recipes like this to be copy and pasted with no understanding of what is happening or why.
    – Chris_F
    Jul 11, 2019 at 5:16
  • It's a bit of black magic, but it works like a charm ;). Here (coliru.stacked-crooked.com/a/90829ec6fc2f95c3) is a snippet that tests all numbers in the ranges [0,31] and [0,63] and does 5<->6 bit conversions.
    – Bim
    May 19 at 15:17
23

You want to map each of these from a 5/6 bit space to an 8 bit space.

  • 5 bits = 32 values
  • 6 bits = 64 values
  • 8 bits = 256 values

The code you're using is taking the naive approach that x5 * 256/32 = x8 where 256/32 = 8 and multiplying by 8 is left shift 3 but, as you say, this doesn't necessarily fill the new number space "correctly". 5 to 8 for max value is 31 to 255 and therein lies your clue to the solution.

x8 = 255/31 * x5
x8 = 255/63 * x6

where x5, x6 and x8 are 5, 6 and 8 bit values respectively.

Now there is a question about the best way to implement this. It does involve division and with integer division you will lose any remainder result (round down basically) so the best solution is probably to do floating point arithmetic and then round half up back to an integer.

This can be sped up considerably by simply using this formula to generate a lookup table for each of the 5 and 6 bit conversions.

3
  • 2
    Just ran a test, and this is equivalent to reusing the top 3 bits, but sometimes it adds or subtracts 1. I guess there’s no real advantage, then.
    – Josh Lee
    Mar 14, 2010 at 15:35
  • codepad.org/qLvbkTO3 This is what it looks like; the bottom 3 bits are mostly following the top 3. I think the only possible way to get more clever is to somehow reverse the dithering that was used :)
    – Josh Lee
    Mar 14, 2010 at 15:41
  • The "add or subtract one" is the important part. Not doing that will tend to amplify the low-precision banding artifacts that 16bit color produces.
    – Alan
    Mar 14, 2010 at 16:44
20

You could shift and then or with the most significant bits; i.e.

Red 10101 becomes 10101000 | 101 => 10101101
    12345         12345---   123    12345123

This has the property you seek, but it's not the most linear mapping of values from one space to the other. It's fast, though. :)

Cletus' answer is more complete and probably better. :)

2
  • 1
    Yes, this is exactly what they’re doing. And I think it’s actually the most linear mapping.
    – Josh Lee
    Mar 14, 2010 at 15:37
  • 1
    It's multiplication by 8.25 with truncation, whereas cletus multiplies by a different value with rounding. Either way, there are 7 "steps" at which adding 1 to the input adds 9 to the output instead of 8. I guess you could define "lack of linearity" in terms of where the steps occur - the variance of the widths of the 8 sections of input, maybe? Or calculate a correlation coefficient on all 32 inputs against their outputs, and the maximum result is the "most linear". Mar 14, 2010 at 16:37
7

iOS vImage Conversion

The iOS Accelerate Framework documents the following algorithm for the vImageConvert_RGB565toARGB8888 function:

Pixel8 alpha = alpha
Pixel8 red   = (5bitRedChannel   * 255 + 15) / 31
Pixel8 green = (6bitGreenChannel * 255 + 31) / 63
Pixel8 blue  = (5bitBlueChannel  * 255 + 15) / 31

For a one-off conversion this will be fast enough, but if you want to process many frames you want to use something like the iOS vImage conversion or implement this yourself using NEON intrinsics.

From ARMs Community Forum Tutorial

First, we will look at converting RGB565 to RGB888. We assume there are eight 16-bit pixels in register q0, and we would like to separate reds, greens and blues into 8-bit elements across three registers d2 to d4.

 vshr.u8      q1, q0, #3      @ shift red elements right by three bits,
                                @  discarding the green bits at the bottom of
                                @  the red 8-bit elements.
vshrn.i16    d2, q1, #5      @ shift red elements right and narrow,
                                @  discarding the blue and green bits.
vshrn.i16    d3, q0, #5      @ shift green elements right and narrow,
                                @  discarding the blue bits and some red bits
                                @  due to narrowing.
vshl.i8      d3, d3, #2      @ shift green elements left, discarding the
                                @  remaining red bits, and placing green bits
                                @  in the correct place.
vshl.i16  q0, q0, #3      @ shift blue elements left to most-significant
                                @  bits of 8-bit color channel.
vmovn.i16    d4, q0          @ remove remaining red and green bits by
                                @  narrowing to 8 bits.

The effects of each instruction are described in the comments above, but in summary, the operation performed on each channel is: Remove color data for adjacent channels using shifts to push the bits off either end of the element. Use a second shift to position the color data in the most-significant bits of each element, and narrow to reduce element size from 16 to eight bits.

Note the use of element sizes in this sequence to address 8 and 16 bit elements, in order to achieve some of the masking operations.

A small problem

You may notice that, if you use the code above to convert to RGB888 format, your whites aren't quite white. This is because, for each channel, the lowest two or three bits are zero, rather than one; a white represented in RGB565 as (0x1F, 0x3F, 0x1F) becomes (0xF8, 0xFC, 0xF8) in RGB888. This can be fixed using shift with insert to place some of the most-significant bits into the lower bits.

For an Android specific example I found a YUV-to-RGB conversion written in intrinsics.

4

Try this:

red5 = (buf & 0xF800) >> 11;
red8 = (red5 << 3) | (red5 >> 2);

This will map all zeros into all zeros, all 1's into all 1's, and everything in between into everything in between. You can make it more efficient by shifting the bits into place in one step:

redmask = (buf & 0xF800);
rgb888 = (redmask << 8) | ((redmask<<3)&0x070000) | /* green, blue */

Do likewise for green and blue (for 6 bits, shift left 2 and right 4 respectively in the top method).

2
  • Yes, this is the solution (but expressed in C, which we didn’t have yet). Except you meant to either divide by 8 or shift right by 3.
    – Josh Lee
    Mar 15, 2010 at 5:41
  • Whoops--shouldn't write these things when half-asleep. Fixed now. Also, should have noticed calmh's solution doing the same thing.
    – Rex Kerr
    Mar 15, 2010 at 13:07
3

The general solution is to treat the numbers as binary fractions - thus, the 6 bit number 63/63 is the same as the 8 bit number 255/255. You can calculate this using floating point math initially, then compute a lookup table, as other posters suggest. This also has the advantage of being more intuitive than bit-bashing solutions. :)

3

There is an error jleedev !!!

unsigned char green = (buf & 0x07c0) >> 5;
unsigned char blue = buf & 0x003f;

the good code

unsigned char green = (buf & 0x07e0) >> 5;
unsigned char blue = buf & 0x001f;

Cheers, Andy

1
  • Good catch. I think this was just a typo in writing the question, though, as the code on my laptop is correct.
    – Josh Lee
    Oct 21, 2010 at 20:36
0

I used the following and got good results. Turned out my Logitek cam was 16bit RGB555 and using the following to convert to 24bit RGB888 allowed me to save as a jpeg using the smaller animals ijg: Thanks for the hint found here on stackoverflow.

// Convert a 16 bit inbuf array to a 24 bit outbuf array
BOOL JpegFile::ByteConvert(BYTE* inbuf, BYTE* outbuf, UINT width, UINT height)
{     UINT row_cnt, pix_cnt;     
      ULONG off1 = 0, off2 = 0;
      BYTE  tbi1, tbi2, R5, G5, B5, R8, G8, B8;

      if (inbuf==NULL)
          return FALSE;

      for (row_cnt = 0; row_cnt <= height; row_cnt++) 
      {     off1 = row_cnt * width * 2;
            off2 = row_cnt * width * 3;
            for(pix_cnt=0; pix_cnt < width; pix_cnt++)
            {    tbi1 = inbuf[off1 + (pix_cnt * 2)];
                 tbi2 = inbuf[off1 + (pix_cnt * 2) + 1];
                 B5 = tbi1 & 0x1F;
                 G5 = (((tbi1 & 0xE0) >> 5) | ((tbi2 & 0x03) << 3)) & 0x1F;
                 R5 = (tbi2 >> 2) & 0x1F;
                 R8 = ( R5 * 527 + 23 ) >> 6;
                 G8 = ( G5 * 527 + 23 ) >> 6;
                 B8 = ( B5 * 527 + 23 ) >> 6;
                 outbuf[off2 + (pix_cnt * 3)] = R8;
                 outbuf[off2 + (pix_cnt * 3) + 1] = G8;
                 outbuf[off2 + (pix_cnt * 3) + 2] = B8;
            }
       }
       return TRUE;
}        
2
  • The question is about 565 so that bit-twiddling and 527 for green won't work.
    – TWiStErRob
    Apr 9, 2016 at 17:37
  • Is that 'row_cnt <= height' clause wrong? Shouldn't it be 'row_cnt < height' ? Nov 20, 2017 at 15:05
0

Here's the code:

namespace convert565888
{
    inline uvec4_t const _c0{ { { 527u, 259u, 527u,  1u } } };
    inline uvec4_t const _c1{ { {  23u,  33u,  23u,  0u } } };
} // end ns

uvec4_v const __vectorcall rgb565_to_888(uvec4_v const rgba) { 
    return(uvec4_v(_mm_srli_epi32(_mm_add_epi32(_mm_mullo_epi32(rgba.v,
           uvec4_v(convert565888::_c0).v), uvec4_v(convert565888::_c1).v), 6)));
}

and for rgb 888 to 565 conversion:

namespace convert888565
{
    inline uvec4_t const _c0{ { {  249u, 509u,  249u,  1u } } };
    inline uvec4_t const _c1{ { { 1014u, 253u, 1014u,  0u } } };
} // end ns

uvec4_v const __vectorcall rgb888_to_565(uvec4_v const rgba) {
    return(uvec4_v(_mm_srli_epi32(_mm_add_epi32(_mm_mullo_epi32(rgba.v,
           uvec4_v(convert888565::_c0).v), uvec4_v(convert888565::_c1).v), 11)));
}

for the explanation of where all these numbers come from, specifically how I calculated the optimal multiplier and bias for green:

Desmos graph - https://www.desmos.com/calculator/3grykboay1

The graph isn't the greatest but it shows the actual value vs. error -- play around with the interactive sliders to see how different values affect the output. This graph also applies to calculating the red and blue values aswell. Typically green is shifted by 10bits, red and blue 11bits. In order for this to work with intrinsic _mm_srli_epi32 / _mm_srl_epi32 requires all components to be shifted by the same amount. So everything is shifted by 11 bits (rgb888_to_565) in this version, however, the green component is scaled to compensate for this change. Fortunately, it scales perfectly!

0

I had this difficulty too, and the most faithful way I found was to replace the 16-bit value with the original 24-bit value. Now the ILI9341 screen color is visually compatible with Notebook screen. I thought of just using the 24-bit color table, but then the display routines would have to be converted to 565, and that would make the program even slower.

If the color palette is fixed as in my case, it might be the most viable option. I tried to make use of the 3 MSB adding with the 3 LSB, but it wasn't very good.

The colors I used on the ILI9341 display I got from this website (Note: I choose the 24-bit color 888 and get the 16-bit color 565, on this website there's no way to do otherwise): http://www.barth-dev.de/online/rgb565-color-picker/

For example, I read the pixel color of the ILI9341 display and save it to a USB Disk, in a file, in BMP format. As the display operates with 16-bit or 18-bit, I have no way to retrieve 24-bit information directly from the GRAM memory.

#define BLACK_565       0x0000
#define BLUE_565        0x001F
#define RED_565         0xF800
#define GREEN_565       0x07E0
#define CYAN_565        0x07FF
#define MAGENTA_565     0xF81F
#define YELLOW_565      0xFFE0
#define WHITE_565       0xFFFF
#define LIGHTGREY_565   0xC618
#define ORANGE_565      0xFD20
#define GREY_565        0x8410
#define DARKGREY_565    0x2104
#define DARKBLUE_565    0x0010
#define DARKGREEN_565   0x03E0
#define DARKCYAN_565    0x03EF
#define DARKYELLOW_565  0x8C40
#define BLUESKY_565     0x047F
#define BROWN_565       0xC408

#define BLACK_888       0x000000
#define BLUE_888        0x0000FF
#define RED_888         0xFF0000
#define GREEN_888       0x04FF00
#define CYAN_888        0x00FFFB
#define MAGENTA_888     0xFF00FA
#define YELLOW_888      0xFBFF00
#define WHITE_888       0xFFFFFF
#define LIGHTGREY_888   0xC6C3C6
#define ORANGE_888      0xFFA500
#define GREY_888        0x808080
#define DARKGREY_888    0x202020
#define DARKBLUE_888    0x000080
#define DARKGREEN_888   0x007D00
#define DARKCYAN_888    0x007D7B
#define DARKYELLOW_888  0x898A00
#define BLUESKY_888     0x008CFF
#define BROWN_888       0xC08240

I did the test (using an STM32F407 uC) with an IF statement, but it can also be done with Select Case, or another form of comparison.

uint16_t buff1; // pixel color value read from GRAM
uint8_t buff2[3];
uint32_t color_buff; // to save to USB disk

if (buff1 == BLUE_565) color_buff = BLUE_888;
else if (buff1 == RED_565) color_buff = RED_888;
else if (buff1 == GREEN_565) color_buff = GREEN_888;
else if (buff1 == CYAN_565) color_buff = CYAN_888;
else if (buff1 == MAGENTA_565) color_buff = MAGENTA_888;
else if (buff1 == YELLOW_565) color_buff = YELLOW_888;
else if (buff1 == WHITE_565) color_buff = WHITE_888;
else if (buff1 == LIGHTGREY_565) color_buff = LIGHTGREY_888;
else if (buff1 == ORANGE_565) color_buff = ORANGE_888;
else if (buff1 == GREY_565) color_buff = GREY_888;
else if (buff1 == DARKGREY_565) color_buff = DARKGREY_888;
else if (buff1 == DARKBLUE_565) color_buff = DARKBLUE_888;
else if (buff1 == DARKCYAN_565) color_buff = DARKCYAN_888;
else if (buff1 == DARKYELLOW_565) color_buff = DARKYELLOW_888;
else if (buff1 == BLUESKY_565) color_buff = BLUESKY_888;
else if (buff1 == BROWN_565) color_buff = BROWN_888;
else color_buff = BLACK;

RGB separation for saving to 8-bit variables:

    buff2[0] = color_buff;       // Blue
    buff2[1] = color_buff >> 8;  // Green
    buff2[2] = color_buff >> 16; // Red

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.