Reputation: 6018
I am trying to map the RGB pixels of an image to 2D arrays of R, G, B seperately.
When the image is read the pixels are stored in a 1D array in the form {r1,g1,b1,r2,g2,b2...}.
The length of array is 3*height*width
. The 2D arrays will be of width X height dimensions
for(i = 0; i < length; i++) { // length = 3*height*width
image[i][2] = getc(f); // blue pixel
image[i][1] = getc(f); // green pixel
image[i][0] = getc(f); // red pixel
img[count] = (unsigned char)image[i][0];
count += 1;
img[count] = (unsigned char)image[i][1];
count += 1;
img[count] = (unsigned char)image[i][2];
count += 1;
printf("pixel %d : [%d,%d,%d]\n", i+1, image[i][0], image[i][1], image[i][2]);
}
The RGB values are in img[]
. The 2d arrays are red[][], green[][] and blue[][].
Please help!
Upvotes: 0
Views: 1711
Reputation: 63481
As I understand it, you are trying to reconstruct the colour fields. Just reverse your function:
unsigned char * imgptr = img;
for( int y = 0; y < height; y++ ) {
for( int x = 0; x < width; x++ ) {
red[y][x] = *imgptr++;
green[y][x] = *imgptr++;
blue[y][x] = *imgptr++;
}
}
To create your arrays dynamically:
unsigned char** CreateColourPlane( int width, int height )
{
int i;
unsigned char ** rows;
const size_t indexSize = height * sizeof(unsigned char*);
const size_t dataSize = width * height * sizeof(unsigned char);
// Allocate memory for row index and data segment. Note, if using C compiler
// do not cast the return value from malloc.
rows = (unsigned char**) malloc( indexSize + dataSize );
if( rows == NULL ) return NULL;
// Index rows. Data segment begins after row index array.
rows[0] = (unsigned char*)rows + height;
for( i = 1; i < height; i++ ) {
rows[i] = rows[i-1] + width;
}
return rows;
}
Then:
unsigned char ** red = CreateColourPlane( width, height );
unsigned char ** green = CreateColourPlane( width, height );
unsigned char ** blue = CreateColourPlane( width, height );
You can free them easily, but it always pays to wrap the free function if you wrapped the allocator function:
void DeleteColourPlane( unsigned char** p )
{
free(p);
}
Upvotes: 2