Necrode
Necrode

Reputation: 51

Printing out a Histogram C++

I am attempting to print out a histogram of values that correspond to the amount of times a pixel value appears in a .pgm file. I know I am reading in the values correctly, it's when I try to print them where I have issues.

int pixelHold[product];

    for(long int i = 0; i < product; i++)
    {
        pixelHold[pixels[i]]++;
        //cout << pixels[i] << ' ' << endl;

    }
    for(long int j = 0; j < product; j++)
    {
        cout << pixelHold[j] << ' ';

    }

"product" is the Width x Height pixel value, which corresponds to the size of the vector I'm using to store all of the values. "pixelHold" is just an array that I'm using to increment every time it comes across a pixel value. For example, it if came across "222" 3 times, it would print a "3" for the "222" slot.

However, the issue is that, when I print the histogram, I get a bunch of zeroes, and then garbage for the last 100 slots or so. When I change the parameters of the for loop to a smaller number, like "221", it prints out the correct histogram up to that point.

Any help is much appreciated!

Upvotes: 0

Views: 2774

Answers (1)

qdot
qdot

Reputation: 6335

You always need to initalize your arrays - otherwise they contain absolutely arbitrary contents - the contents of RAM where the compiler decided to put your array.

Also, your histogram table should have the dimensions of 256 - since that's how many (8-bit) colors there are in a greyscale image.

The following code should do the trick:

const int histogramLevels = 256;
int pixelHold[histogramLevels];

for (int i=0; i<histogramLevels; i++) pixelHold[i] = 0;

for(long int i = 0; i < product; i++)
{
    pixelHold[pixels[i]]++;
    //cout << pixels[i] << ' ' << endl;

}

for (int i=0; i<histogramLevels; i++) {
    cout << pixelHold[j] << ' ';
}

Upvotes: 1

Related Questions