gpt4 book ai didi

c++ - 写入 .PGM 图像会导致形状困惑

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:44:17 31 4
gpt4 key购买 nike

我正在尝试读取和重写 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

最佳答案

@Lightness Races in Orbit 是对的。您需要将数据读取为二进制数据。您还混淆了行和列:宽度是列,高度是行。此外,您不需要字符串流。

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

读取所有头部信息:
image >> inputLine >> col >> row >> max_val;

创建行 x 列矩阵:
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);

关于c++ - 写入 .PGM 图像会导致形状困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42414971/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com