0

这是我到目前为止使用搜索功能的第一篇文章。但是现在我在以下问题上浪费了一整天:

我录制了一个 12 位(写为 16 位)灰度视频,并将其直接写入二进制流文件(没有标题等)。

现在的任务是读取文件并将每一帧输出为 16 位 pgm。

以下截图说明了我尝试过的内容。输出是有效的 pgm,但带有“白噪声”。

    ...
    imageBufferShort = new short[imageWidth*imageHeight* sizeof(short)];
    ...
    streamFileHandle.read(reinterpret_cast<char*>(imageBufferShort),2*imageWidth*imageHeight); //double amount because 8bit chars!
    // As .read only takes chars, I thought, that I just read the double amount of char-bytes and when it is interpreted as short (=16bit) everything is ok?!?

    ...now the pgm output:

    std::ofstream f_hnd(fileName,std::ios_base::out |std::ios_base::binary |std::ios_base::trunc);
    // write simple header
    f_hnd.write("P5\n",3);
    f_hnd << imageWidth << " " << imageHeight << "\n4095\n";  //4095 should tell the pgm to use 2 bytes for each pixel

    f_hnd.write(reinterpret_cast<char*>(imageBufferShort),2*imageWidth*imageHeight);
    f_hnd.close();

同样,该文件已生成并可查看,但包含垃圾。最初的猜测可以吗?阅读2个“字符”并将它们作为一个“短”处理?我还在每一行之后尝试了一个空格,但这没有任何改变,所以我决定发布这个更短的代码。

谢谢你的帮助!

4

2 回答 2

1

正如@Domi 和@JoeZ 指出的那样:您的字节序可能搞砸了。意思是,你的字节顺序是错误的。

要解决您的问题,您必须遍历每个像素并交换它的字节,然后再将其写回文件。

于 2013-11-29T08:24:11.507 回答
0

问题解决了。非常感谢大家。Endianess确实是问题所在。解决方案如下:

    f_hnd << "P5" << " " << imDimensions.GetWidth() << " " << imDimensions.GetHeight() << " " << "4095\n";

    // convert imageBufferShort to Big-Endian format
    unsigned short imageBufferShortBigEndian[imDimensions.GetWidth()*imDimensions.GetHeight()];

    for (int k=0 ; k<imDimensions.GetWidth()*imDimensions.GetHeight() ; k++)
    {
        imageBufferShortBigEndian[k] = ( (imageBufferShort[k] << 8) | (imageBufferShort[k] >> 8) );
    }

    f_hnd.write(reinterpret_cast<char*>(imageBufferShortBigEndian),2*imDimensions.GetWidth()*imDimensions.GetHeight());
    f_hnd.close();

imageBufferShort 也有一个无符号短数组。如果使用有符号类型,则位移转换会稍微困难一些。

再次感谢!

于 2013-12-02T09:20:22.183 回答