GRASS GIS 8 Programmer's Manual  8.5.0dev(2024)-36359e2344
histo_eq.c
Go to the documentation of this file.
1 /**************************************************************
2  * Rast_histogram_eq (histo, map, min, max)
3  *
4  * struct Histogram *histo; histogram as returned by Rast_read_histogram()
5  * unsigned char **map; equalized category mapping
6  * CELL *min, *max; min,max category for map
7  *
8  * perform histogram equalization
9  * inputs are histo, output is map,min,max
10  ****************************************************************/
11 #include <grass/gis.h>
12 #include <grass/raster.h>
13 
14 void Rast_histogram_eq(const struct Histogram *histo, unsigned char **map,
15  CELL *min, CELL *max)
16 {
17  int i;
18  int x;
19  CELL cat, prev;
20  double total;
21  double sum;
22  double span;
23  int ncats;
24  long count;
25  unsigned char *xmap;
26  int len;
27  int first, last;
28 
29  ncats = Rast_get_histogram_num(histo);
30  if (ncats == 1) {
31  *min = *max = Rast_get_histogram_cat(0, histo);
32  *map = xmap = (unsigned char *)G_malloc(1);
33  *xmap = 0;
34  return;
35  }
36  if ((*min = Rast_get_histogram_cat(first = 0, histo)) == 0)
37  *min = Rast_get_histogram_cat(++first, histo);
38  if ((*max = Rast_get_histogram_cat(last = ncats - 1, histo)) == 0)
39  *max = Rast_get_histogram_cat(--last, histo);
40  len = *max - *min + 1;
41  *map = xmap = (unsigned char *)G_malloc(len);
42 
43  total = 0;
44  for (i = first; i <= last; i++) {
45  if (Rast_get_histogram_cat(i, histo) == 0)
46  continue;
47  count = Rast_get_histogram_count(i, histo);
48  if (count > 0)
49  total += count;
50  }
51  if (total <= 0) {
52  for (i = 0; i < len; i++)
53  xmap[i] = 0;
54  return;
55  }
56 
57  span = total / 256;
58 
59  sum = 0.0;
60  cat = *min - 1;
61  for (i = first; i <= last; i++) {
62  prev = cat + 1;
63  cat = Rast_get_histogram_cat(i, histo);
64  count = Rast_get_histogram_count(i, histo);
65  if (count < 0 || cat == 0)
66  count = 0;
67  x = (sum + (count / 2.0)) / span;
68  if (x < 0)
69  x = 0;
70  else if (x > 255)
71  x = 255;
72  sum += count;
73 
74  while (prev++ <= cat)
75  *xmap++ = x;
76  }
77 }
#define G_malloc(n)
Definition: defs/gis.h:94
int Rast_get_histogram_num(const struct Histogram *)
Sorts the histogram in ascending order by counts then category.
Definition: histogram.c:159
long Rast_get_histogram_count(int, const struct Histogram *)
Returns count for the nth element in the histogram.
Definition: histogram.c:187
CELL Rast_get_histogram_cat(int, const struct Histogram *)
Returns cat for the nth element in the histogram.
Definition: histogram.c:171
#define min(x, y)
Definition: draw2.c:29
#define max(x, y)
Definition: draw2.c:30
int CELL
Definition: gis.h:628
void Rast_histogram_eq(const struct Histogram *histo, unsigned char **map, CELL *min, CELL *max)
Definition: histo_eq.c:14
int count
#define x