0

我正在编写一个简单的程序来将灰度二进制 (P5) 转换为灰度 ascii (P2),但是在读取二进制并将其转换为 int 时遇到问题。

#include <iostream>
#include <fstream>
#include <sstream>
using namespace::std;

int usage(char* arg) {
// exit program
    cout << arg << ": Error" << endl;
    return -1;
}

int main(int argc, char* argv[]) {
    int rows, cols, size, greylevels;
    string filetype;

    // open stream in binary mode
    ifstream istr(argv[1], ios::in | ios::binary);
    if(istr.fail()) return usage(argv[1]);

    // parse header
    istr >> filetype >> rows >> cols >> greylevels;
    size = rows * cols;

    // check data
    cout << "filetype: " << filetype << endl;
    cout << "rows: " << rows << endl;
    cout << "cols: " << cols << endl;
    cout << "greylevels: " << greylevels << endl;
    cout << "size: " << size << endl;

    // parse data values
    int* data = new int[size];
    int fail_tracker = 0; // find which pixel failing on
    for(int* ptr = data; ptr < data+size; ptr++) {
        char t_ch;
        // read in binary char
        istr.read(&t_ch, sizeof(char));
        // convert to integer
        int t_data = static_cast<int>(t_ch);
        // check if legal pixel
        if(t_data < 0 || t_data > greylevels) { 
            cout << "Failed on pixel: " << fail_tracker << endl;
            cout << "Pixel value: " << t_data << endl;
            return usage(argv[1]);
        }
        // if passes add value to data array
        *ptr = t_data;
        fail_tracker++;
    }
    // close the stream
    istr.close();

    // write a new P2 binary ascii image
    ofstream ostr("greyscale_ascii_version.pgm");
    // write header
    ostr << "P2 " << rows << cols << greylevels << endl;
    // write data
    int line_ctr = 0;
    for(int* ptr = data; ptr < data+size; ptr++) {
        // print pixel value
        ostr << *ptr << " ";
        // endl every ~20 pixels for some readability
        if(++line_ctr % 20 == 0) ostr << endl;
    }
    ostr.close();

    // clean up
    delete [] data;
    return 0;
}

示例图片- 从旧帖子中提取。删除了图像文件中的注释,因为我现在不担心这个功能。

当用 g++ 编译时,我得到输出:

$> ./a.out a.pgm
filetype: P5
rows: 1024
cols: 768
greylevels: 255
size: 786432
Failed on pixel: 1
Pixel value: -110
a.pgm: Error

图像是一只小鸭子,像素值不可能是-110 ......我哪里出错了?谢谢。

4

3 回答 3

2

灰度:255

-110 是 146 作为无符号字符。看来您在 char 是有符号类型的平台上,请尝试使用 unsigned char。

于 2012-10-26T17:12:35.350 回答
0

如果您不能有负值,请使用 anunsigned int *而不是int*您的像素指针。这样您就不会将值读取为有符号值

于 2012-10-26T17:01:27.613 回答
0

您需要更正输出:

ostr << "P2\n" << rows << " "<< cols << " "<<  greylevels << endl;
于 2015-07-09T14:32:13.650 回答