gpt4 book ai didi

c - 如何在c中读取图像的像素?

转载 作者:行者123 更新时间:2023-11-30 14:42:06 25 4
gpt4 key购买 nike

Suppose our bitmap image has height M and width N. We'll always assume in this lab that the width N is a multiple of 4, which simplifies the byte layout in the file. For this image, the pixel array stores exactly 3 x N x M bytes, in the following way:

Each group of 3 bytes represents a single pixel, where the bytes store the blue, green, and red colour values of the pixel, in that order.

Pixels are grouped by row. For example, the first 3 x N bytes in the pixel array represent the pixels in the top-most row of the image.

pixel_array_offset 是像素数组的起始位置。

结构体像素如下:

struct pixel {
unsigned char blue;
unsigned char green;
unsigned char red;
};

这里是实现该功能的要求:

/*
* Read in pixel array by following these instructions:
*
* 1. First, allocate space for m "struct pixel *" values, where m is the
* height of the image. Each pointer will eventually point to one row of
* pixel data.
* 2. For each pointer you just allocated, initialize it to point to
* heap-allocated space for an entire row of pixel data.
* 3. ...
* 4. ...
*/
struct pixel **read_pixel_array(FILE *image, int pixel_array_offset, int width, int height) {

}

第一步,为 m 个“struct Pixel *”值分配空间。我认为它实际上是为像素值数组分配空间。所以我把

unsigned char **ptrs = height * malloc(sizeof(struct pixel));

对于第二步,我不太明白我应该做什么。我想我需要一个 for 循环来为所有像素数据行分配空间。但我不知道该放什么进去。

for (int i=0, i<height, i++) {

}

最佳答案

既然要分配一个2D数组,那么首先需要分配一个struct Pixel *数组:

struct pixel **ptrs = malloc(height * sizeof(struct pixel*));

这里有几处变化需要注意:

  1. 您正在分配指向struct Pixel的指针,而不是unsigned char
  2. malloc() 返回一个指针。指针乘以整数是无效的。
  3. 乘法放在括号中,因为它有助于计算要分配的正确字节数。

接下来,您需要为 2D 数组中的每一行分配一个 struct Pixel 数组:

for (int i=0, i<height, i++) {
ptrs[i] = malloc(width * sizeof(struct pixel));
}

现在数组已完全分配,您可以用数据填充它:

ptrs[5][6] = { 255, 0, 0}; // a blue pixel

最后记住在退出程序之前free()所有指针:

for (int i=0, i<height, i++) {
free(ptrs[i]);
}

free(ptrs);

关于c - 如何在c中读取图像的像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54601450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com