Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm for slicing planes (in place) out of an array of RGB values

I've got a flat array of byte RGB values that goes R1 G1 B1 R2 G2 B2 R3 G3 B3 ... Rn Gn Bn. So my data looks like:

char imageData[WIDTH * HEIGHT * 3];

But I want to pass a WIDTH*HEIGHT array to an existing C library that expects a single plane of this data. That would be a sequence of just the R values (or just the G, or just the B).

It's easy enough to allocate a new array and copy the data (duh). But the images are very large. If it weren't a C library but took some kind of iteration interface to finesse the "slicing" traversal, that would be great. But I can't edit the code I'm calling...it wants a plain old pointer to a block of sequential memory.

HOWEVER I have write access to this array. It is viable to create a routine that would sort it into color planes. I'd also need a reverse transformation that would put it back, but by definition the same method that sorted it into planes could be applied to unsort it.

How efficiently can I (in place) turn this array into R1 R2 R3 ... Rn G1 G2 G3 ... Gn B1 B2 B3 ... Bn and then back again? Any non-naive algorithms?

like image 513
HostileFork says dont trust SE Avatar asked Dec 11 '11 17:12

HostileFork says dont trust SE


1 Answers

If you only need one plane, this seems pretty easy. If you need all 3 you will probably have better luck with a more sophisticated algorithm.

void PlanarizeR(char * imageData, int width, int height)
{
    char *in = imageData;
    int pixelCount = width * height;
    for (int i = 0;  i < pixelCount;  ++i, in+=3)
        std::swap(*in, imageData[i])
}

It shouldn't be too hard to run the loop backwards from high to low to reverse the process.

like image 164
Mark Ransom Avatar answered Sep 24 '22 11:09

Mark Ransom