I31 Answer ― Histogram


#include <stdlib.h>
#include <stdio.h>
#include "../basicImage.c"
void statistics( image img, double *avg, double *sd ) { int r, c, value ; double sum = 0.0; double sumOfSquares = 0.0; double avgSumOfSquares = 0.0; for ( r=0; r<img.nrows; r++ ) for ( c=0; c<img.ncols; c++ ) { value = getPixel( img, r, c ) ; sum += value; sumOfSquares += value*value; } *avg = sum/(img.nrows*img.ncols); avgSumOfSquares = sumOfSquares/(img.nrows*img.ncols); *sd = sqrt( avgSumOfSquares - *avg * *avg ); } void histogram ( image img, int histo[] ) { int r, c, j, value; for ( j=0; j<255; j++ ) histo[j] = 0; for ( r=0; r<img.nrows; r++ ) for ( c=0; c<img.ncols; c++ ) { value = getPixel( img, r, c ) ; histo[value]++ ; } } void displayHist( int histo[] ) { const int maxStars = 15; /* number of stars maximum in a column */ const int displayWidth = 64; int compHisto[displayWidth]; int pixPerStar; int gray; int r, c, j, line, max; /* compress the histogram for a compact display */ for ( j=0; j<displayWidth; j++ ) compHisto[j] = histo[j*4]+histo[j*4+1]+histo[j*4+2]+histo[j*4+3]; /* Scan for maximum value in compressed histogram */ max = compHisto[0]; for ( j=0; j<displayWidth; j++ ) if ( compHisto[j] > max ) max = compHisto[j]; /* How many pixels per star? */ pixPerStar = max/maxStars; /* Print the Histogram */ for ( line=maxStars; line>0; line-- ) { printf("| "); for ( gray=0; gray<displayWidth ; gray++ ) if ( compHisto[gray] >= pixPerStar*line ) printf("*"); else printf(" "); printf("\n"); } /* Print the Horizontal Axis */ printf("-"); printf("-"); for ( gray=0; gray<displayWidth; gray++ ) printf("-"); printf("\n"); } int main ( int argc, char* argv[] ) { image img; double average, stdDev ; int hist[256] = { 0 }; if ( argc != 2 ) { printf("histogram imageFile\n"); exit( EXIT_FAILURE ); } /* read in the image */ readPGMimage( &img, argv[1]); /* compute statistics and histogram */ statistics( img, &average, &stdDev ) ; histogram ( img, hist ); /* display the results */ displayHist( hist ); printf("average: %lf\tstandard deviation: %lf\n", average, stdDev) ; /* free memory */ freeImage( &img ); }

Comments: