# How can I convert an OpenCV Mat of type CV_8UC3 pixel data to an unsigned int* in ARGB format?

I need a pointer unsigned int* data, such that,

an unsigned int (32 bits) holds a pixel in ARGB format, which from left to right is as follows:

the first 8 bits are for the alpha channel (and are ignored) the next 8 bits are for the red channel the next 8 bits are for the green channel the last 8 bits are for the blue channl

edit retag close merge delete

could you please remove the other question ? one should be enough.

Sort by » oldest newest most voted

unfortunately there's no builtin support for ARGB with opencv , so there's no easy, straightforward solution.

you could try a double-for loop like this:

unsigned int * pixels = new unsigned int [ 4 * img.total() ];
int k=0;
for ( int i=0; i<img.rows; i++ ) {
for ( int j=0; j<img.rows; j++ ) {
Vec3b p = img.at<Vec3b>(i,j);
// a ( skipped )
pixels[k]  = p << 16; // r
pixels[k] |= p << 8;  // g
pixels[k] |= p;       // b
k++;
}
}
// now process pixels

// ofc, later, you'll have to cleanup
delete [] pixels;

more

Later, if I want to retrieve these rgb values, how can I do that?

2

from the unsigned int * pointer ?

unsigned int p = pixels[i];

uchar r =(p>>16) & 0xff;

uchar g =(p>>8) & 0xff;

uchar b =(p) & 0xff;

it's just the reverse..

2

it should basically work like that:

int r = (pixel & 0x00FF0000) >> 16;

int g = (pixel & 0x0000FF00) >> 8;

int b = (pixel & 0x000000FF);

int a = (pixel & 0xFF000000) >> 24;

Those numbers are basically bitmasks extracting only the part that is responsible for the channel.

Btw, you can also add the alpha channel (imread also supports this). You just need Vec4b p = img.at<Vec4b> and then pixels[k] = p << 24;

lol, Moster, i got : first shift, then mask, you got the opposite. is it actually the same ? i think so.

actually i think, your version is more clear on what ends up where

Yes, its doing the same. It should also have exactly the same performance.

Official site

GitHub

Wiki

Documentation