adaptive_histogram_equalization.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. //
  2. // Copyright 2020 Debabrata Mandal <mandaldebabrata123@gmail.com>
  3. //
  4. // Use, modification and distribution are subject to the Boost Software License,
  5. // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt)
  7. //
  8. #ifndef BOOST_GIL_IMAGE_PROCESSING_ADAPTIVE_HISTOGRAM_EQUALIZATION_HPP
  9. #define BOOST_GIL_IMAGE_PROCESSING_ADAPTIVE_HISTOGRAM_EQUALIZATION_HPP
  10. #include <boost/gil/algorithm.hpp>
  11. #include <boost/gil/histogram.hpp>
  12. #include <boost/gil/image.hpp>
  13. #include <boost/gil/image_processing/histogram_equalization.hpp>
  14. #include <boost/gil/image_view_factory.hpp>
  15. #include <cmath>
  16. #include <map>
  17. #include <vector>
  18. namespace boost { namespace gil {
  19. /////////////////////////////////////////
  20. /// Adaptive Histogram Equalization(AHE)
  21. /////////////////////////////////////////
  22. /// \defgroup AHE AHE
  23. /// \brief Contains implementation and description of the algorithm used to compute
  24. /// adaptive histogram equalization of input images. Naming for the AHE functions
  25. /// are done in the following way
  26. /// <feature-1>_<feature-2>_.._<feature-n>ahe
  27. /// For example, for AHE done using local (non-overlapping) tiles/blocks and
  28. /// final output interpolated among tiles , it is called
  29. /// non_overlapping_interpolated_clahe
  30. ///
  31. namespace detail {
  32. /// \defgroup AHE-helpers AHE-helpers
  33. /// \brief AHE helper functions
  34. /// \fn double actual_clip_limit
  35. /// \ingroup AHE-helpers
  36. /// \brief Computes the actual clip limit given a clip limit value using binary search.
  37. /// Reference - Adaptive Histogram Equalization and Its Variations
  38. /// (http://www.cs.unc.edu/techreports/86-013.pdf, Pg - 15)
  39. ///
  40. template <typename SrcHist>
  41. double actual_clip_limit(SrcHist const& src_hist, double cliplimit = 0.03)
  42. {
  43. double epsilon = 1.0;
  44. using value_t = typename SrcHist::value_type;
  45. double sum = src_hist.sum();
  46. std::size_t num_bins = src_hist.size();
  47. cliplimit = sum * cliplimit;
  48. long low = 0, high = cliplimit, middle = low;
  49. while (high - low >= 1)
  50. {
  51. middle = (low + high + 1) >> 1;
  52. long excess = 0;
  53. std::for_each(src_hist.begin(), src_hist.end(), [&](value_t const& v) {
  54. if (v.second > middle)
  55. excess += v.second - middle;
  56. });
  57. if (std::abs(excess - (cliplimit - middle) * num_bins) < epsilon)
  58. break;
  59. else if (excess > (cliplimit - middle) * num_bins)
  60. high = middle - 1;
  61. else
  62. low = middle + 1;
  63. }
  64. return middle / sum;
  65. }
  66. /// \fn void clip_and_redistribute
  67. /// \ingroup AHE-helpers
  68. /// \brief Clips and redistributes excess pixels based on the actual clip limit value
  69. /// obtained from the other helper function actual_clip_limit
  70. /// Reference - Graphic Gems 4, Pg. 474
  71. /// (http://cas.xav.free.fr/Graphics%20Gems%204%20-%20Paul%20S.%20Heckbert.pdf)
  72. ///
  73. template <typename SrcHist, typename DstHist>
  74. void clip_and_redistribute(SrcHist const& src_hist, DstHist& dst_hist, double clip_limit = 0.03)
  75. {
  76. using value_t = typename SrcHist::value_type;
  77. double sum = src_hist.sum();
  78. double actual_clip_value = detail::actual_clip_limit(src_hist, clip_limit);
  79. // double actual_clip_value = clip_limit;
  80. long actual_clip_limit = actual_clip_value * sum;
  81. double excess = 0;
  82. std::for_each(src_hist.begin(), src_hist.end(), [&](value_t const& v) {
  83. if (v.second > actual_clip_limit)
  84. excess += v.second - actual_clip_limit;
  85. });
  86. std::for_each(src_hist.begin(), src_hist.end(), [&](value_t const& v) {
  87. if (v.second >= actual_clip_limit)
  88. dst_hist[dst_hist.key_from_tuple(v.first)] = clip_limit * sum;
  89. else
  90. dst_hist[dst_hist.key_from_tuple(v.first)] = v.second + excess / src_hist.size();
  91. });
  92. long rem = long(excess) % src_hist.size();
  93. if (rem == 0)
  94. return;
  95. long period = round(src_hist.size() / rem);
  96. std::size_t index = 0;
  97. while (rem)
  98. {
  99. if (dst_hist(index) >= clip_limit * sum)
  100. {
  101. index = (index + 1) % src_hist.size();
  102. }
  103. dst_hist(index)++;
  104. rem--;
  105. index = (index + period) % src_hist.size();
  106. }
  107. }
  108. } // namespace detail
  109. /// \fn void non_overlapping_interpolated_clahe
  110. /// \ingroup AHE
  111. /// @param src_view Input Source image view
  112. /// @param dst_view Output Output image view
  113. /// @param tile_width_x Input Tile width along x-axis to apply HE
  114. /// @param tile_width_y Input Tile width along x-axis to apply HE
  115. /// @param clip_limit Input Clipping limit to be applied
  116. /// @param bin_width Input Bin widths for histogram
  117. /// @param mask Input Specify if mask is to be used
  118. /// @param src_mask Input Mask on input image to ignore specified pixels
  119. /// \brief Performs local histogram equalization on tiles of size (tile_width_x, tile_width_y)
  120. /// Then uses the clip limit to redistribute excess pixels above the limit uniformly to
  121. /// other bins. The clip limit is specified as a fraction i.e. a bin's value is clipped
  122. /// if bin_value >= clip_limit * (Total number of pixels in the tile)
  123. ///
  124. template <typename SrcView, typename DstView>
  125. void non_overlapping_interpolated_clahe(
  126. SrcView const& src_view,
  127. DstView const& dst_view,
  128. std::ptrdiff_t tile_width_x = 20,
  129. std::ptrdiff_t tile_width_y = 20,
  130. double clip_limit = 0.03,
  131. std::size_t bin_width = 1.0,
  132. bool mask = false,
  133. std::vector<std::vector<bool>> src_mask = {})
  134. {
  135. gil_function_requires<ImageViewConcept<SrcView>>();
  136. gil_function_requires<MutableImageViewConcept<DstView>>();
  137. static_assert(
  138. color_spaces_are_compatible<
  139. typename color_space_type<SrcView>::type,
  140. typename color_space_type<DstView>::type>::value,
  141. "Source and destination views must have same color space");
  142. using source_channel_t = typename channel_type<SrcView>::type;
  143. using dst_channel_t = typename channel_type<DstView>::type;
  144. using coord_t = typename SrcView::x_coord_t;
  145. std::size_t const channels = num_channels<SrcView>::value;
  146. coord_t const width = src_view.width();
  147. coord_t const height = src_view.height();
  148. // Find control points
  149. std::vector<coord_t> sample_x;
  150. coord_t sample_x1 = tile_width_x / 2;
  151. coord_t sample_y1 = tile_width_y / 2;
  152. auto extend_left = tile_width_x;
  153. auto extend_top = tile_width_y;
  154. auto extend_right = (tile_width_x - width % tile_width_x) % tile_width_x + tile_width_x;
  155. auto extend_bottom = (tile_width_y - height % tile_width_y) % tile_width_y + tile_width_y;
  156. auto new_width = width + extend_left + extend_right;
  157. auto new_height = height + extend_top + extend_bottom;
  158. image<typename SrcView::value_type> padded_img(new_width, new_height);
  159. auto top_left_x = tile_width_x;
  160. auto top_left_y = tile_width_y;
  161. auto bottom_right_x = tile_width_x + width;
  162. auto bottom_right_y = tile_width_y + height;
  163. copy_pixels(src_view, subimage_view(view(padded_img), top_left_x, top_left_y, width, height));
  164. for (std::size_t k = 0; k < channels; k++)
  165. {
  166. std::vector<histogram<source_channel_t>> prev_row(new_width / tile_width_x),
  167. next_row((new_width / tile_width_x));
  168. std::vector<std::map<source_channel_t, source_channel_t>> prev_map(
  169. new_width / tile_width_x),
  170. next_map((new_width / tile_width_x));
  171. coord_t prev = 0, next = 1;
  172. auto channel_view = nth_channel_view(view(padded_img), k);
  173. for (std::ptrdiff_t i = top_left_y; i < bottom_right_y; ++i)
  174. {
  175. if ((i - sample_y1) / tile_width_y >= next || i == top_left_y)
  176. {
  177. if (i != top_left_y)
  178. {
  179. prev = next;
  180. next++;
  181. }
  182. prev_row = next_row;
  183. prev_map = next_map;
  184. for (std::ptrdiff_t j = sample_x1; j < new_width; j += tile_width_x)
  185. {
  186. auto img_view = subimage_view(
  187. channel_view, j - sample_x1, next * tile_width_y,
  188. std::max<int>(
  189. std::min<int>(tile_width_x + j - sample_x1, bottom_right_x) -
  190. (j - sample_x1),
  191. 0),
  192. std::max<int>(
  193. std::min<int>((next + 1) * tile_width_y, bottom_right_y) -
  194. next * tile_width_y,
  195. 0));
  196. fill_histogram(
  197. img_view, next_row[(j - sample_x1) / tile_width_x], bin_width, false,
  198. false);
  199. detail::clip_and_redistribute(
  200. next_row[(j - sample_x1) / tile_width_x],
  201. next_row[(j - sample_x1) / tile_width_x], clip_limit);
  202. next_map[(j - sample_x1) / tile_width_x] =
  203. histogram_equalization(next_row[(j - sample_x1) / tile_width_x]);
  204. }
  205. }
  206. bool prev_row_mask = 1, next_row_mask = 1;
  207. if (prev == 0)
  208. prev_row_mask = false;
  209. else if (next + 1 == new_height / tile_width_y)
  210. next_row_mask = false;
  211. for (std::ptrdiff_t j = top_left_x; j < bottom_right_x; ++j)
  212. {
  213. bool prev_col_mask = true, next_col_mask = true;
  214. if ((j - sample_x1) / tile_width_x == 0)
  215. prev_col_mask = false;
  216. else if ((j - sample_x1) / tile_width_x + 1 == new_width / tile_width_x - 1)
  217. next_col_mask = false;
  218. // Bilinear interpolation
  219. point_t top_left(
  220. (j - sample_x1) / tile_width_x * tile_width_x + sample_x1,
  221. prev * tile_width_y + sample_y1);
  222. point_t top_right(top_left.x + tile_width_x, top_left.y);
  223. point_t bottom_left(top_left.x, top_left.y + tile_width_y);
  224. point_t bottom_right(top_left.x + tile_width_x, top_left.y + tile_width_y);
  225. long double x_diff = top_right.x - top_left.x;
  226. long double y_diff = bottom_left.y - top_left.y;
  227. long double x1 = (j - top_left.x) / x_diff;
  228. long double x2 = (top_right.x - j) / x_diff;
  229. long double y1 = (i - top_left.y) / y_diff;
  230. long double y2 = (bottom_left.y - i) / y_diff;
  231. if (prev_row_mask == 0)
  232. y1 = 1;
  233. else if (next_row_mask == 0)
  234. y2 = 1;
  235. if (prev_col_mask == 0)
  236. x1 = 1;
  237. else if (next_col_mask == 0)
  238. x2 = 1;
  239. long double numerator =
  240. ((prev_row_mask & prev_col_mask) * x2 *
  241. prev_map[(top_left.x - sample_x1) / tile_width_x][channel_view(j, i)] +
  242. (prev_row_mask & next_col_mask) * x1 *
  243. prev_map[(top_right.x - sample_x1) / tile_width_x][channel_view(j, i)]) *
  244. y2 +
  245. ((next_row_mask & prev_col_mask) * x2 *
  246. next_map[(bottom_left.x - sample_x1) / tile_width_x][channel_view(j, i)] +
  247. (next_row_mask & next_col_mask) * x1 *
  248. next_map[(bottom_right.x - sample_x1) / tile_width_x][channel_view(j, i)]) *
  249. y1;
  250. if (mask && !src_mask[i - top_left_y][j - top_left_x])
  251. {
  252. dst_view(j - top_left_x, i - top_left_y) =
  253. channel_convert<dst_channel_t>(
  254. static_cast<source_channel_t>(channel_view(i, j)));
  255. }
  256. else
  257. {
  258. dst_view(j - top_left_x, i - top_left_y) =
  259. channel_convert<dst_channel_t>(static_cast<source_channel_t>(numerator));
  260. }
  261. }
  262. }
  263. }
  264. }
  265. }} //namespace boost::gil
  266. #endif