[Solved] Open a pgm image 16 bpp [closed]


i’ve found solution to my problem. here is the right code if it can be useful for someone:

#include "pgm.h"

#include <iterator>
#include <algorithm>
#include <fstream>
#include <sstream>

using namespace std;

bool convert16to8bit(const std::string& inFilename, mat<uint8_t>& img, const std::string& outFilename){
    mat<uint16_t> imgTemp;

    ifstream is(inFilename, ios::binary);
    if (!is)
        return false;

    string magic;
    is >> magic;
    if (magic != "P2" && magic != "P5")
        return false;

    size_t rows, cols, nlevels;
    is >> cols >> rows >> nlevels;

    if (nlevels < 255)
        return false;

    is.get();

    img = mat<uint8_t>(rows, cols);
    if (nlevels == 255){
        if (magic == "P5"){
            is.unsetf(ios::skipws);
            img.data_.assign(istream_iterator<uint8_t>(is), istream_iterator<uint8_t>());
        }else
            img.data_.assign(istream_iterator<int>(is), istream_iterator<int>());
    }
    else{
        imgTemp = mat<uint16_t>(rows, cols);
        if (magic == "P5"){

            //here is the line changed
            is.read(reinterpret_cast<char *>(&imgTemp.data_[0]), imgTemp.rows()*imgTemp.cols() * 2);          
        }
        else
            imgTemp.data_.assign(istream_iterator<int>(is), istream_iterator<int>());

        for (size_t r = 0; r < rows; r++)
            for (size_t c = 0; c < cols; c++)
                img(r, c) = imgTemp(r, c);
    }

    stringstream ss; 
    ss << outFilename << ".pgm";
    ofstream os(ss.str(), ios::binary);
    if (!os)
        return false;
    os << magic <<"\n" << cols << " " << rows << "\n255\n";
    if (magic == "P2") 
        copy(begin(img), end(img), ostream_iterator<int>(os, " ")); 
    else 
        copy(begin(img), end(img), ostream_iterator<uint8_t>(os));

    return true;
}

solved Open a pgm image 16 bpp [closed]