Picture.pbm -->十进制,在 c++ 中

Picture.pbm --> decimal, in c++

本文关键字:c++ 十进制 pbm gt Picture      更新时间:2023-10-16

只是想问是否有人知道为什么我不能将整个图片转换为十进制。

问题:大约 180 次后,其余像素变为 0。

法典:

#include <fstream>
#include <iostream>
int main() {
    char unsigned charTemp = 0;
    int unsigned intTemp = 0;
    std::fstream file;
    file.open("PIC.pbm", std::ios::in);
    //Ignore header
    for (int i = 0; i < 13; i++) {
    file.ignore();
    }
    //read and print
    //img res is 40x40 = 1600
    for (int i = 0; i < 1600; i++) {
        file >> charTemp;
        intTemp = charTemp;
        std::cout << intTemp << " ";
        charTemp = 0;
        intTemp = 0;
    }
    std::cout << "nnn";
    system("pause");
    return 0;
}

图片:任何 40x40 pbm

图片和图像文件的更好方法是将它们读取为binary文件:

std::ifstream file("PIC.pbm", ios::binary);
std::vector<unsigned char> bitmap(1600);
// Skip over the header
file.seekg(13, ios::beg); // Skip over 13 bytes.
// Read in the data at once
file.read((char *) &bitmap[0], 1600);
// Now process the bitmap from memory
for (int i = 0; i < 1600; ++i)
{
  cout << static_cast<unsigned int>(bitmap[i]) << " ";
  if ((i % 40) == 39)
  {
    cout << "n";
  }
}
cout << "n";

这里的想法是将一个事务中的位图读入内存。 流喜欢流动(不要中断流(。 内存的访问速度比文件快,因此位图值是从内存中处理的。

使用强制转换,以便格式化插入不会将字节视为字符,而是将数字视为数字。

首先,在另一个十六进制编辑器中打开您的PIC.pbm文件,因为这些字节很可能真的是零。如果没有,那么您在读取文件时遇到问题。

fstream构造函数不默认以二进制模式读取,因此它将文件读取为"文本" - 我已经学到了艰难的方式,你不能再相信标准库对文本有任何了解(如何处理 Unicode、行尾等 - 我觉得最好始终使用 binary 和专用的 Unicode 库(。

您应该在每次读取操作后检查 fstream::good() 函数以查看它是否失败,如果是,请检查iostate

using namespace std;
// ...
fstream file;
file.open( "PIC.pbm", ios::in | ios::binary );
file.ignore( 13 );
for (int i = 0; i < 1600; i++) {
    file >> charTemp;
    if( !file.good() ) {
        cout << endl;
        cout << "Error reading file: iostate == " << file.iostate << endl;
        break;
    }
    else {
        intTemp = charTemp;
        std::cout << intTemp << " ";
        charTemp = 0;
        intTemp = 0;
    }
}