gpt4 book ai didi

C 将 PPM 图像显示为文本

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

我是 C 编程新手,正在尝试文件操作,我正在尝试输出一个 PPM 文件及其注释和 RGB 数据值,如下所示:

P3
# The same image with width 3 and height 2,
# using 0 or 1 per color (red, green, blue)
3 2 1
1 0 0 0 1 0 0 0 1
1 1 0 1 1 1 0 0 0

在这个程序中,我已经能够检查它是否具有正确的格式并读入结构,但我遇到的问题是如何收集 RGB 数据然后将其打印出来。这是我到目前为止所拥有的。显示此信息的方法是我已经启动的 showPPM 结构,但不知道如何读取图像结构并收集其 rgb 值并显示它,任何帮助都会很棒。

#include<stdio.h>
#include<stdlib.h>

typedef struct {
unsigned char red,green,blue;
} PPMPixel;

typedef struct {
int x, y;
PPMPixel *data;
} PPMImage;


static PPMImage *readPPM(const char *filename)
{
char buff[16];
PPMImage *img;
FILE *fp;
int c, rgb_comp_color;
//open PPM file for reading
fp = fopen(filename, "rb");
if (!fp) {
fprintf(stderr, "Unable to open file '%s'\n", filename);
exit(1);
}

//read image format
if (!fgets(buff, sizeof(buff), fp)) {
perror(filename);
exit(1);
}

//check the image format
if (buff[0] != 'P' || buff[1] != '3') {
fprintf(stderr, "Invalid image format (must be 'P6')\n");
exit(1);
}

//alloc memory form image
img = (PPMImage *)malloc(sizeof(PPMImage));
if (!img) {
fprintf(stderr, "Unable to allocate memory\n");
exit(1);
}

//check for comments
c = getc(fp);
while (c == '#') {
while (getc(fp) != '\n') ;
c = getc(fp);
}

ungetc(c, fp);
//read image size information
if (fscanf(fp, "%d %d", &img->x, &img->y) != 2) {
fprintf(stderr, "Invalid image size (error loading '%s')\n", filename);
exit(1);
}

while (fgetc(fp) != '\n') ;
//memory allocation for pixel data
img->data = (PPMPixel*)malloc(img->x * img->y * sizeof(PPMPixel));

if (!img) {
fprintf(stderr, "Unable to allocate memory\n");
exit(1);
}

//read pixel data from file
if (fread(img->data, 3 * img->x, img->y, fp) != img->y) {
fprintf(stderr, "Error loading image '%s'\n", filename);
exit(1);
}

fclose(fp);
return img;
}

void showPPM(struct * image){
int rgb_array[600][400];
int i;
int j;

for(i = 0; i<600; i++)
{
for(j = 0; j<400; j++)
{
printf("%d", rgb_array[i][j]);
}
}
}


int main(){
PPMImage *image;
image = readPPM("aab.ppm");
showPPM(image);
}

最佳答案

您的代码看起来很可疑:

read PPM file and store it in an array; coded with C

对此也有一些非常好的评论和帮助。

所以,我留下下面的其他内容作为进一步的帮助:

<小时/>

这里开始有点模糊,让你有机会自己解决它......

首先,您需要将整个 ppm 文件读入缓冲区。 fread() 可能是为此选择的函数。您可以使用ftell()来获取文件的大小。接下来,您可以在 fread() 使用的缓冲区顶部对 PPMImage 结构进行类型转换,并且从那里,您应该能够通过 data 字段访问数据,如果您愿意,甚至可以使用数组表示法。 (我认为这是您现在缺少的步骤......)

一旦您可以访问数据,您应该能够根据输入数据迭代数据和 printf() 或控制台所需的任何内容。

关于C 将 PPM 图像显示为文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41750380/

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