2015-04-06 42 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; 
}