Go Down

Topic: translating shifts from Java (Processing) to C++ (arduino) (Read 2 times) previous topic - next topic

lloyddean

If I understand the basis of your original question you wish to convert a source pixel buffer of  'rrrrrggggggbbbbb' values to a gray scale equivalent destination pixel buffer.

The following code fragment should accomplish that ...

Code: [Select]

struct rgb_t
{
    union {
        struct {
            unsigned _b:5;
            unsigned _g:6;
            unsigned _r:5;
        };
        uint16_t    _rgb;
    };
   
    rgb_t(uint8_t r, uint8_t g, uint8_t b)
        : _r(r), _g(g), _b(b)
    {}
   
    rgb_t(uint16_t rgb)
        : _rgb(rgb)
    {}

    operator uint16_t() const { return _rgb; };
    uint8_t red()   const     { return _r;   };
    uint8_t green() const     { return _g;   };
    uint8_t blue()  const     { return _b;   };
};


uint8_t bufSrc[32];    // color pixel buffer
uint8_t bufDst[32];    // gray scale buffer

// convert the color pixel buffer 'bufSrc' to an average gray scale pixel buffer 'bufDst'

rgb_t* pSrc = (rgb_t*)bufSrc;
rgb_t* pDst = (rgb_t*)bufDst;

for (uint16_t i = sizeof(bufSrc) / 2; i--; )
{
    rgb_t    pixelSrc = *pSrc++;
    uint8_t  average  = (pixelSrc.red() + (pixelSrc.green() >> 1) + pixelSrc.blue());
    *pDst++ = rgb_t(average, average << 1, average);
}


robvoi

You are correct. I try to converto 16 bit rgb to 8 bit and 4 bit grayscale.
Your code looks very clean. Creating a struct/class is really good, if reused often. Thanks for the input and example.

Do you expect your code to be more efficient or does the compiler translate my "beginner style" code to something equal?

Robert


lloyddean

The above example code is converting from 16-bit color to 16-bit gray scale.

What do you mean by converting to 8 bit and 4 bit grayscale.

rrrrrggggggbbbbb -> what 8-bit
rrrrrggggggbbbbb -> what 4-bit

robvoi

I mean:
16 bit RGB = 1 pixel per 2 byte -> RRRRRGGGGGGBBBBB
8 bit grayscale = 1 pixel per byte -> GGGGGGGG

                                                 pix1    pix2
4 bit grayscale = 2 pixel per byte -> GGGG GGGG

It's working with the code provided by robtillaart. Yours is more compat but also (for me) more complaex to read.
If it ismore efficient regarding storage space or calculation time, I will try to implement it.

Thanks
Robert

Go Up