我知道没有理由在 C++ 上实现一个读取 pgm 图像的像素值的函数,但我必须为我的任务做这件事。
出于准确性原因,在读取像素值后,我将其与使用 imread(file) 在 matlab 中读取的像素值进行了比较,但是,有些值匹配,有些不匹配,我不知道为什么。
下面是c++的函数,图片是二进制格式:
int Read_File_PGM(string filename){
int row = 0, col = 0, numrows = 0, numcols = 0, bits;
string filename;
ifstream infile(filename.c_str(), ios::binary);
stringstream ss;
string inputLine = "";
// First line : version
getline(infile,inputLine);
if(inputLine.compare("P5") != 0) cerr << "Version error" << endl;
//else cout << "Version : " << inputLine << endl;
// Second line : width and height
ss << infile.rdbuf();
ss >> numrows >> numcols;
int max_bits;
ss >> max_bits;
unsigned char pixel;
unsigned int pixel_value[numrows][numcols];
//double sum = 0;
// Following lines : data
for(row = 0; row < numrows; ++row){
for (col = 0; col < numcols; ++col){
infile.read(pixel, 1);
ss >> pixel;
pixel_value[row][col] = (int)pixel;
}
}
infile.close();
}
return 0;
}