【发布时间】:2019-01-02 20:29:40
【问题描述】:
我目前正在做一个需要输出生成图像的项目。由于其简单性,我决定使用灰度netbpm format。这些图像之一是高度图。我的导出代码如下:
#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;
}
在阅读the specification for the netbpm format on Wikipedia 之后,这段代码对我来说是正确的。然而,当我尝试在 Gimp 或 Clion 中打开此图像时,会出现各种错误:
文件以pgm 扩展名保存。我的代码有什么问题?
【问题讨论】:
-
您可以发一个minimal reproducible example 或SSCCE。
-
unsigned char brightness = m_data[i]*256;看起来不对。你想用它做什么? -
@NathanOliver m_data 是 [0, 1] 范围内双精度数的 std::array,并且是 HeightMap 的成员对象。我将每个双精度转换为范围 [0, 255] 并将其存储为 unsigned char,因为 unsigned char 的内部二进制格式与 netbpm 格式匹配。 m_data 中的每个无符号字符或条目仅包含一个像素。
-
所以乘以 255!
-
您可以使用说明性输入重现问题并提供给我们,正如 Jesper 链接到的文章所解释的那样。你应该在调试阶段就这样做了!
标签: c++ binary-data pgm