请问各位有没有用C++ opencv读.pfm代码,我从GitHub下载的几个在我这里运行不对
该回答引用ChatGPT
下面是一个简单的示例代码,可以读取.pfm文件并将其转换为OpenCV的Mat对象:
#include <opencv2/opencv.hpp>
#include <fstream>
using namespace cv;
using namespace std;
Mat readPFM(const string& filename)
{
ifstream file(filename, ios::binary);
if (!file)
{
cerr << "Error: could not open file " << filename << endl;
return Mat();
}
string format;
file >> format;
if (format != "PF")
{
cerr << "Error: unsupported file format " << format << endl;
return Mat();
}
int width, height;
file >> width >> height;
float scale;
file >> scale;
Mat image(height, width, CV_32FC3);
file.ignore(1, '\n');
for (int i = height - 1; i >= 0; i--)
{
float* row_ptr = image.ptr<float>(i);
for (int j = 0; j < width; j++)
{
file.read(reinterpret_cast<char*>(row_ptr), sizeof(float) * 3);
row_ptr += 3;
}
}
file.close();
return image;
}
int main()
{
Mat image = readPFM("example.pfm");
if (image.empty())
{
return -1;
}
imshow("image", image);
waitKey(0);
return 0;
}
在这个示例中,readPFM()函数读取.pfm文件并返回一个OpenCV的Mat对象。要读取.pfm文件,需要使用ifstream类,它允许从文件中读取二进制数据。读取.pfm文件的第一行应该是文件格式,应该是字符串"PF"。接下来是宽度和高度,然后是缩放因子。最后,文件中的每个像素由三个32位浮点数表示(对于RGB图像)。由于.pfm文件中的像素从底部开始存储,因此在读取像素时需要从底部开始读取。
在主函数中,我们只是调用readPFM()函数并显示读取的图像。