我正在编写一个程序,通过获取输入PGM,将数据存储在vector<unsigned char>中,使用数据 vector 创建新 vector 等来操作PGM文件,依此类推,直到我使用最后一个 vector 创建输出PGM文件为止。 。
我每次都迈出了一步,从输入PGM并将数据放入vector<unsigned char>开始,然后获取原始 vector 并将其输出到新的PGM文件中。基本上,将输入复制到新文件中。它不起作用,我不确定为什么。
这是我的代码:

//note: int degree is for after I start manipulating the data and dimensions will change
void outputFile(vector<unsigned char> image, int degree, int original_r, int original_c){
FILE* pgmimg;
pgmimg = fopen("pgmimg.PGM", "wb");
int temp;

int width = static_cast<int>(original_c / (pow(2, degree)));
int height = static_cast<int>(original_r / (pow(2, degree)));

fprintf(pgmimg, "P2\n");
fprintf(pgmimg, "%d %d\n", width, height);
fprintf(pgmimg, "255\n");

for (int i = 0; i < height; i++){
    for (int k = 0; k < width; k++){
        temp = image[(i*width)+k];

        fprintf(pgmimg, "%d ", temp);
    }
    fprintf(pgmimg, "\n");
}
fclose(pgmimg);}

int main(){
// PATH_NAME is a string defined at the beginning of the code set to the path to the input image
fstream img;
img.open(PATH_NAME, ios::in | ios::binary | ios::out);

string line;
getline(img, line);
if(!img.is_open()){
    cout << "Unable to open image" << endl;
    return 0;
}
if(!line.compare("P2")){
    cout << "Incorrect file format" << endl;
    return 0;
}

getline(img, line);
istringstream iss(line);
string row_string, col_string;
iss >> col_string;
iss >> row_string;

int original_rows = stoi(row_string);
int original_cols = stoi(col_string);

cout << original_rows << " " << original_cols << endl;
getline(img, line); //get max value

//collect data from input
int length = img.tellg();
char* buffer = new char [length];
img.read (buffer, length);
//copy data into original
vector<unsigned char> original(original_rows*original_cols);
for(int i = 0; i < original.size(); i++){
    original[i] = buffer[i];
}
outputFile(original, 0, original_rows, original_cols);
img.close();
return 0;
}
这就是我要输入的内容(StackOverflow不允许我放置PGM,所以这是PNG版本):c&#43;&#43; - 从vector &lt;unsigned char&gt;写入PGM文件-LMLPHP
这是在“pgmimg.PGM”中输出的:c&#43;&#43; - 从vector &lt;unsigned char&gt;写入PGM文件-LMLPHP
显然,这是完全错误的(正确的尺寸,其他所有错误)。有人可以帮助我或让我知道在读取输入或写入输出时遇到问题吗?谢谢。

最佳答案

输入代码看起来错误

int length = img.tellg();
char* buffer = new char [length];
img.read (buffer, length);
tellg是文件中的当前位置。这与剩余要读取的数据量无关。只需将数据直接读入 vector
vector<unsigned char> original(original_rows*original_cols);
img.read(original.data(), original.size());

关于c++ - 从vector <unsigned char>写入PGM文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63982548/

10-11 16:28