hello hello - 1 year ago 58
C++ Question

distorted image in pgm binary file manipulation

I'm trying to perform convolution on a

image of type
with the set up below:

input and output array

vector<vector<char>> image(rows, vector<char>(cols, '\0'));
vector<vector<char>> out(rows, vector<char>(cols, '\0'));

const int SIZE = 3;


vector<vector<int>> filter = { { 0, -1, 0 }, { -1, 5, -1 }, { 0, -1, 0 } };

insert binary data into image array

I'm reading PGM file like this:

getline(infile, type);
//getline(infile, comment);
infile >> rows >> cols;
getline(infile, line);
getline(infile, highest);
//getline(infile, line);

for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
infile >> image[i][j]; //infile is from filestream


//Insert default header attributes into output pgm file.
outfile << type << "\n" << rows << " " << cols << "\n" << maxpx << "\n";

for (int i = SIZE / 2; i < rows - SIZE / 2; i++)
for (int j = SIZE / 2; j < cols - SIZE / 2; j++)
uint8_t sum = 0;
for (int k = -SIZE / 2; k <= SIZE / 2; k++)
for (int l = -SIZE / 2; l <= SIZE / 2; l++)
sum += image[i+k][j+l] * filter[k + SIZE / 2][l + SIZE / 2];
out[i][j] = sum;

Write binary data into out file

for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
outfile << out[i][j];

I do not get any error when I run the code, but the image is distorted. I can clearly make out some part of the output image, but it's is not coming out complete.

Not sure if it has to do with my manipulation.


I changed
to char, but I still get the same error.

  1. When I change
    outfile << out[i][j];
    outfile << image[i][j];
    so I can get the actual image back, but looks like there could be some issues with how I'm reading the file into
    vector. Not sure how to at this point.
    I get this imageenter image description here

Lena.pgm file


Answer Source

I am no expert on C++, but I believe you cannot (or maybe should not) use the >> operator to read binary files.

I worked this out by noticing that your image goes wrong where there are black pixels and I believe that these null bytes are being interpreted incorrectly by ifstream when you don't actually want them interpreted at all. I decreased the contrast on your image so the range of the pixels was no longer 0-255 but 67-197 and it all works. So it works when there are no low values in your image.

I believe you need to change the way you read the binary image data from:

infile >> image[i][j];

to something like:


or maybe something using get(). Sorry, I cannot be more precise, as C++ is not my forte but hopefully you can now proceed further. If anyone cares to explain what I am saying in a comment - please feel free to teach me! Thank you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download