【问题标题】:How to mapping a 1d array to a 2d array in C?如何将一维数组映射到C中的二维数组?
【发布时间】:2013-01-23 21:37:49
【问题描述】:

我正在尝试将图像的 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[][]。

请帮忙!

【问题讨论】:

  • 你的代码看起来好像它已经在做,但恰恰相反。

标签: c image-processing multidimensional-array


【解决方案1】:

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

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

【讨论】:

  • f 在代码 sn -p 是图像文件。当我运行它时,我得到一个堆栈溢出错误!
  • 你的意思是你在堆栈上声明了每个二维数组?是的,这可能会给你一个堆栈溢出。我假设您已经将它们设置为动态数组。如果没有,请告诉我,我可以发表评论。
  • 看看我昨天对这个问题的回答:stackoverflow.com/a/14459359/1553090 - 问题已关闭,但现在它仍然可用。在那个答案中,我给出了一些技巧,可以让创建动态 2D 数组变得不那么痛苦。
  • 我在循环之前执行了此操作,但出现错误 a value of type void* cannot be usedto initialize an entity of int**
  • 哦,对了,这可能意味着您正在使用 C++ 编译器。我以为你在使用 C。在这种情况下,只需将 malloc 的结果转换为 int**(或者,正如我更正的那样,unsigned char**)。
猜你喜欢
  • 1970-01-01
  • 2011-01-10
  • 1970-01-01
  • 2014-09-03
  • 1970-01-01
  • 1970-01-01
  • 2016-11-22
  • 1970-01-01
相关资源
最近更新 更多