0

我正在尝试将图像的 RGB 像素分别映射到 R、G、B 的二维数组。读取图像时,像素以 {r1,g1,b1,r2,g2,b2...} 的形式存储在 1D 数组中。数组的长度为3*height*width。二维数组的宽度 X 高度

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]);
}

RGB 值在img[]. 二维数组是 red[][]、green[][] 和 blue[][]。

请帮忙!

4

1 回答 1

2

据我了解,您正在尝试重建色域。只需反转您的功能:

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++;
    }
}

动态创建数组:

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;
}

然后:

unsigned char ** red = CreateColourPlane( width, height );
unsigned char ** green = CreateColourPlane( width, height );
unsigned char ** blue = CreateColourPlane( width, height );

你可以很容易地释放它们,但如果你包装了分配器函数,包装释放函数总是值得的:

void DeleteColourPlane( unsigned char** p )
{
    free(p);
}
于 2013-01-23T21:47:01.497 回答