[英]What is wrong with my code to write netbpm images?
我目前正在从事一个需要输出生成图像的项目。 由于其简单性,我决定使用灰度netbpm格式 。 这些图像之一是高度图。 我要导出的代码如下:
#include <array>
#include <fstream>
#include <iostream>
int main(){
constexpr unsigned LENGTH = 4;
std::array<double, LENGTH*LENGTH> m_data = {
0, 0, 0, 0,
0, 1, 1, 0,
0, 1, 1, 0,
0, 0, 0, 0
};
std::ofstream fout;
fout.exceptions(std::ios::badbit | std::ios::failbit);
fout.open("test.pgm", std::ios::binary);
fout << "P5 " << LENGTH << " " << LENGTH << "\n256\n";
for(unsigned i=0;i<LENGTH*LENGTH;++i){
unsigned char brightness = m_data[i]*255;
std::cout << m_data[i] << std::endl;
fout.write(reinterpret_cast<char*>(&brightness), sizeof(unsigned char));
}
return 0;
}
在阅读Wikipedia上netbpm格式的规范后,这段代码对我来说看起来是正确的。 但是,当我尝试在Gimp或Clion中打开此图像时,会出现各种错误:
该文件以pgm
扩展名保存。 我的代码有什么问题?
尝试像这样编写NetPBM标头:
fout << "P5\n" << LENGTH << " " << LENGTH << "\n255\n";
原因是大多数图像读取器都会检查MAXVAL,如果小于或等于255,则假定每个像素为8位。 如果MAXVAL超过255,则它们假定每个像素16位,因此他们会抱怨您的文件太短(因为它不提供每个像素2个字节)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.