histo_eq.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. void Rast_histogram_eq(const struct Histogram *histo,
  14. unsigned char **map, CELL * min, CELL * max)
  15. {
  16. int i;
  17. int x;
  18. CELL cat, prev;
  19. double total;
  20. double sum;
  21. double span;
  22. int ncats;
  23. long count;
  24. unsigned char *xmap;
  25. int len;
  26. int first, last;
  27. ncats = Rast_get_histogram_num(histo);
  28. if (ncats == 1) {
  29. *min = *max = Rast_get_histogram_cat(0, histo);
  30. *map = xmap = (unsigned char *)G_malloc(1);
  31. *xmap = 0;
  32. return;
  33. }
  34. if ((*min = Rast_get_histogram_cat(first = 0, histo)) == 0)
  35. *min = Rast_get_histogram_cat(++first, histo);
  36. if ((*max = Rast_get_histogram_cat(last = ncats - 1, histo)) == 0)
  37. *max = Rast_get_histogram_cat(--last, histo);
  38. len = *max - *min + 1;
  39. *map = xmap = (unsigned char *)G_malloc(len);
  40. total = 0;
  41. for (i = first; i <= last; i++) {
  42. if (Rast_get_histogram_cat(i, histo) == 0)
  43. continue;
  44. count = Rast_get_histogram_count(i, histo);
  45. if (count > 0)
  46. total += count;
  47. }
  48. if (total <= 0) {
  49. for (i = 0; i < len; i++)
  50. xmap[i] = 0;
  51. return;
  52. }
  53. span = total / 256;
  54. sum = 0.0;
  55. cat = *min - 1;
  56. for (i = first; i <= last; i++) {
  57. prev = cat + 1;
  58. cat = Rast_get_histogram_cat(i, histo);
  59. count = Rast_get_histogram_count(i, histo);
  60. if (count < 0 || cat == 0)
  61. count = 0;
  62. x = (sum + (count / 2.0)) / span;
  63. if (x < 0)
  64. x = 0;
  65. else if (x > 255)
  66. x = 255;
  67. sum += count;
  68. while (prev++ <= cat)
  69. *xmap++ = x;
  70. }
  71. }