about summary refs log tree commit diff
path: root/analyzer/pgmhist.c
blob: 8f4e512eb8f17c5dd3be4885ec4fc7e3d005e4ab (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* pgmhist.c - print a histogram of the values in a portable graymap
**
** Copyright (C) 1989 by Jef Poskanzer.
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation.  This software is provided "as is" without express or
** implied warranty.
*/

#include "pgm.h"
#include "mallocvar.h"

int
main( argc, argv )
    int argc;
    char *argv[];
{
    FILE *ifp;
    gray maxval, *grayrow;
    register gray *gP;
    int argn, rows, cols, format, row;
    int i, *hist, *rcount, count, size;
    register int col;
    const char * const usage = "[pgmfile]";

    pgm_init( &argc, argv );

    argn = 1;

    if ( argn < argc )
	{
        ifp = pm_openr( argv[argn] );
        argn++;
	}
    else
        ifp = stdin;

    if ( argn != argc )
        pm_usage( usage );

    pgm_readpgminit( ifp, &cols, &rows, &maxval, &format );
    grayrow = pgm_allocrow( cols );

    /* Build histogram. */
    MALLOCARRAY(hist, maxval + 1);
    MALLOCARRAY(rcount, maxval + 1);
    if ( hist == NULL || rcount == NULL )
        pm_error( "out of memory" );
    for ( i = 0; i <= maxval; i++ )
        hist[i] = 0;
    for ( row = 0; row < rows; row++ )
	{
        pgm_readpgmrow( ifp, grayrow, cols, maxval, format );
        for ( col = 0, gP = grayrow; col < cols; col++, gP++ )
            hist[(int) *gP]++;
	}

    pm_close( ifp );

    /* Compute count-down */
    count = 0;
    for ( i = maxval; i >= 0; i-- )
	{
        count += hist[i];
        rcount[i] = count;
	}

    /* And print it. */
    printf( "value\tcount\tb%%\tw%%\n" );
    printf( "-----\t-----\t--\t--\n" );
    count = 0;
    size = rows * cols;
    for ( i = 0; i <= maxval; i++ )
        if ( hist[i] > 0 )
	    {
            count += hist[i];
            printf(
                "%d\t%d\t%5.3g%%\t%5.3g%%\n", i, hist[i],
                (float) count * 100.0 / size, 
                (float) rcount[i] * 100.0 / size );
	    }

    exit( 0 );
}