2015-04-06 50 views
0

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

倒置画面

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

当写入的像素数据,这条线

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

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

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


在一个不相关的音符,你不每一行后打印一个换行符,因此产生的PPM文件实际上是不正确的。

+0

我明白你的意思了。我只是把最初的读入函数取下来,稍微颠倒过来,所以我明白为什么覆盖它不是我想要的 – yup

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