2017-02-23 2 views
2

Ich versuche, ein PGM-Bild zu lesen und neu zu schreiben, obwohl es in orientierungsloser Form resultiert. Das rechte Bild das Original ist, ist die linke die neu erstellte ein:Schreiben .PGM-Bild führt zu orientierungsloser Form

Example of problem

Dies ist der Code, ich verwende:

#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(); 
} 

, was mache ich falsch?

the original image header

+0

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

+0

@LightnessRacesinOrbit ich bereits aufgebaut entsprechend dem Format, und ich erhalte die Ergebnisse, wie Sie in der linken Seite von Das Bild – Ibrahim

+0

Sieht für mich aus wie Sie binäre Format angeben, aber interpretieren und geben Sie die Zeilen- und Spalteninformationen im ASCII-Format –

Antwort

0

@Lightness Rennen in Orbit ist richtig. Sie müssen Daten als Binärdaten lesen. Sie haben auch Zeile und Spalte verwechselt: Breite ist Spalte, Höhe ist Zeile. Außerdem benötigen Sie keinen Stringstream.

öffnet image als Binärdatei:
ifstream image("3.pgm", ios::binary);

Lesen Sie die ganze Kopfinfo:
image >> inputLine >> col >> row >> max_val;

eine Zeile x col Matrix erstellen:
vector< vector<unsigned char> > array(row, vector<unsigned char>(col));

liest in binären Daten :

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

oder

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

öffnen Ausgabedatei im Binärmodus:
ofstream newfile("z.pgm", ios::binary);

schreiben Kopfinfo: newfile << "P5" << endl << col << " " << row << endl << max_val << endl;

Schreiben aus binäre Daten:

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

oder

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

das hat es getan. Vielen Dank ! – Ibrahim

Verwandte Themen