反转PPM图像的值

时间:2015-04-06 14:54:04

标签: c

我用C语言编写,我必须编写能够反转图像中每个像素的RGB值的代码。这是一个简单的过程,您可以获取最大颜色值并减去实际的RGB值。我已经成功读取了最大颜色值,但是当试图反转这些值时,所有内容都返回0并且当写入新文件时无法读取。以下是代码,任何想法?

反转图片

int i,j;
for(i=0; i<myPic->rows;++i) {
    //Moves up and down the columns reaching all Pixels
    //Moves across left to right across all columns
    for (j=0;j<myPic->cols;++j) {
    //Inverstion requires the actual value to be subtracted from the max
        myPic->pixels[i][j].red = myPic->colors - myPic->pixels[i][j].red;
        myPic->pixels[i][j].green = myPic->colors - myPic->pixels[i][j].green;
        myPic->pixels[i][j].blue = myPic->colors - myPic->pixels[i][j].blue;
        }
    }
return myPic;

}

输出图像

fprintf(name,"P3\n%d %d\n%d\n",myPic->rows,myPic->cols,myPic->colors);
//The P3,rows,columns,and color values are all printed first
int i,j;
for(i=0; i< myPic->rows;++i) {
        for(j=0; j<myPic->cols;++j) { //Each Pixel is printed one at a time
        fprintf(name,"%d",myPic->pixels[i][j].red); //Red printed first
        fprintf(name,"%d",myPic->pixels[i][j].green); //Green printed second
        fprintf(name,"%d",myPic->pixels[i][j].blue); //Blue printed third
        fprintf("\n");
        }
    }

}

感谢帮助人员,这就是我现在正在使用的工具

2 个答案:

答案 0 :(得分:2)

写入像素数据时,此行

myPic->pixels[i] = malloc(sizeof(Pixel) *myPic->cols);

覆盖现有指针,并指向新的(更重要的是未初始化的)数据。

复制粘贴编程(您似乎一直在做)有时可以工作,但您必须注意正确修改复制的代码。


在不相关的注释中,您不会在每行之后打印换行符,因此生成的PPM文件实际上不正确。

答案 1 :(得分:0)

@Joachim是对的。所以做这样的事情:

int i,j;
for(i=0; i<myPic->rows;++i) {

    Pixel[myPic->cols] temp = *myPic->pixels[i];

    //Moves up and down the columns reaching all Pixels
    myPic->pixels[i] = malloc(sizeof(Pixel) *myPic->cols);
    //Moves across left to right across all columns
    for (j=0;j<myPic->cols;++j) {
    //Inverstion requires the actual value to be subtracted from the max
        myPic->pixels[i][j].red = myPic->colors - temp[j].red;
        myPic->pixels[i][j].green = myPic->colors - temp[j].green;
        myPic->pixels[i][j].blue = myPic->colors - temp[j].blue;
        }
    }
    return myPic;
}