2017-02-23 55 views
2

我正在嘗試讀取並重新寫入PGM圖像,但它會導致無法定向的形狀。右邊的圖像是原單,左邊是重新創建一個:寫入.PGM圖像會導致無法定向的形狀

Example of problem

這是代碼我使用:

#include <iostream> 
#include <string> 
#include <fstream> 
#include <sstream> 

using namespace std; 

int main() 
{ 
int row = 0, col = 0, num_of_rows = 0, max_val = 0; 
stringstream data; 
ifstream image ("3.pgm"); 

string inputLine = ""; 

getline (image, inputLine); // read the first line : P5 
data << image.rdbuf(); 
data >> row >> col >> max_val; 
cout << row << " " << col << " " << max_val << endl; 
static float array[11000][5000] = {}; 
unsigned char pixel ; 

for (int i = 0; i < row; i++) 
{ 
    for (int j = 0; j < col; j++) 
    { 
     data >> pixel; 
     array[j][i] = pixel; 



    } 
} 

ofstream newfile ("z.pgm"); 
newfile << "P5 " << endl << row << " " << col << " " << endl << max_val << endl; 

for (int i = 0; i < row; i++) 
{ 
    for (int j = 0; j < col; j++) 
    { 

     pixel = array[j][i]; 

     newfile << pixel; 


    } 

} 

image.close(); 
newfile.close(); 
} 

我究竟做錯了什麼?

the original image header

+0

https://en.wikipedia.org/wiki/Netpbm_format#File_format_description –

+0

@LightnessRacesinOrbit我已經按照格式建造,而我得到的結果就像你在左側看到圖像 – Ibrahim

+0

在我看來,你指定的是二進制格式,但是解釋並給出ASCII格式的行和列信息 –

回答

0

@Lightness種族在軌道是正確的。您需要將數據讀取爲二進制數據。你也混合了行和列:寬度是col,高度是行。你也不需要一個stringstream。

打開image爲二進制文件:
ifstream image("3.pgm", ios::binary);

閱讀所有的頭信息:在二進制數據
vector< vector<unsigned char> > array(row, vector<unsigned char>(col));

閱讀:
image >> inputLine >> col >> row >> max_val;

創建一個行X山坳矩陣:

for (int i = 0; i < row; i++) 
    for (int j = 0; j < col; j++) 
     image.read(reinterpret_cast<char*>(&array[i][j]), 1); 

for (int i = 0; i < row; i++) 
    image.read(reinterpret_cast<char*>(&array[i][0]), col); 

打開輸出文件,在二進制模式:
ofstream newfile("z.pgm", ios::binary);

寫頭信息: newfile << "P5" << endl << col << " " << row << endl << max_val << endl;

寫出二進制數據:

for (int i = 0; i < row; i++) 
    for (int j = 0; j < col; j++) 
     newfile.write(reinterpret_cast<const char*>(&array[i][j]), 1); 

for (int i = 0; i < row; i++) 
    newfile.write(reinterpret_cast<const char*>(&array[i][0]), col); 
+0

做到了。謝謝 ! – Ibrahim