I am trying to implement a C++ code to read a binary PBM file. Right now, after read the header of the file successfully (magic number, width and height), I got this code to read each character of the file, and extract the individual bits from this character:
std::vector<pixel> v;
char c;
while(input_file.get(c)) {
for(int i=0; i<8; i++) {
pixel p;
p.r = p.g = p.b = (c & (1 << i)) != 0;
v.push_back(p);
}
}
After that, I transfer the data of this vector to a matrix:
int h = stoi(height), w = stoi(width);
int counter = 0;
for(int i=0; i<h; i++) {
std::vector<pixel> row;
for(int j=0; j<w; j++) row.push_back(v[counter++]);
image.push_back(row);
}
With that, when I try visualize the image on the screen, I got a distorted image, where some pixels seems to be dislocated from its original position. I got the following program that generate a ascii image that shows what I got after read the binary file:
struct Pixel {
int r, g, b;
};
typedef struct Pixel pixel;
int main(int argc, char *argv[])
{
if(argc < 3) return 1;
std::string input = argv[1];
std::string output = argv[2];
std::ifstream input_file(input);
std::ofstream output_file(output);
std::vector<std::vector<pixel>> image;
std::vector<pixel> v;
std::string line_one, line_two, line_pixels;
char magicNumber;
std::string width, height;
while(getline(input_file, line_one)) {
if(line_one.size() > 0 && line_one.at(0) != '#') {
magicNumber = line_one.at(1);
break;
}
}
while(getline(input_file, line_two)) {
if(line_two.size() > 0 && line_two.at(0) != '#') {
std::stringstream ss(line_two);
getline(ss, width, ' ');
getline(ss, height, ' ');
break;
}
}
std::cout << magicNumber << std::endl;
std::cout << width << " " << height << std::endl;
if(magicNumber == '4') {
std::vector<pixel> v;
char c;
while(input_file.get(c)) {
for(int i=0; i<8; i++) {
pixel p;
p.r = p.g = p.b = (c & (1 << i)) != 0;
v.push_back(p);
}
}
int h = stoi(height), w = stoi(width);
int counter = 0;
for(int i=0; i<h; i++) {
std::vector<pixel> row;
for(int j=0; j<w; j++) row.push_back(v[counter++]);
image.push_back(row);
}
}
output_file << "P1" << std::endl << width << " " << height << std::endl;
for(int i=0; i<stoi(height); i++) {
for(int j=0; j<stoi(width); j++) {
output_file << image[i][j].r << " ";
}
output_file << std::endl;
}
return 0;
}
The image I am trying to read in my tests is this one. Anyone can tell me what's wrong here? How I can get the same image after read the file?