写作.PGM图像会导致形状失调

时间:2017-02-23 11:49:19

标签: c++ image image-processing 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

1 个答案:

答案 0 :(得分:0)

在轨道上的@Lightness Races是对的。您需要将数据读取为二进制数据。你还混合了row和col:width是col,height是row。你也不需要字符串流。

以二进制文件打开image
ifstream image("3.pgm", ios::binary);

阅读所有标题信息:
image >> inputLine >> col >> row >> max_val;

创建一行x col矩阵:
vector< vector<unsigned char> > array(row, vector<unsigned char>(col));

读入二进制数据:

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