getting_started_listing_04.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2019 Hans Dembinski
  2. //
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt
  5. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. // clang-format off
  7. //[ getting_started_listing_04
  8. #include <algorithm> // std::max_element
  9. #include <boost/format.hpp> // only needed for printing
  10. #include <boost/histogram.hpp> // make_histogram, integer, indexed
  11. #include <iostream> // std::cout, std::endl
  12. #include <sstream> // std::ostringstream
  13. int main() {
  14. using namespace boost::histogram;
  15. using namespace boost::histogram::literals;
  16. /*
  17. We make a 3d histogram for color values (r, g, b) in an image. We assume the values
  18. are of type char. The value range then is [0, 256). The integer axis is perfect for
  19. color values.
  20. */
  21. auto h = make_histogram(
  22. axis::integer<>(0, 256, "r"),
  23. axis::integer<>(0, 256, "g"),
  24. axis::integer<>(0, 256, "b")
  25. );
  26. /*
  27. We don't have real image data, so fill some fake data.
  28. */
  29. h(1, 2, 3);
  30. h(1, 2, 3);
  31. h(0, 1, 0);
  32. /*
  33. Now let's say we want to know which color is most common. We can use std::max_element
  34. on an indexed range for that.
  35. */
  36. auto ind = indexed(h);
  37. auto max_it = std::max_element(ind.begin(), ind.end());
  38. /*
  39. max_it is a special iterator to the histogram cell with the highest count.
  40. This iterator allows one to access the cell value, bin indices, and bin values.
  41. You need to twice dereference it to get to the cell value.
  42. */
  43. std::ostringstream os;
  44. os << boost::format("count=%i rgb=(%i, %i, %i)")
  45. % **max_it % max_it->bin(0_c) % max_it->bin(1) % max_it->bin(2);
  46. std::cout << os.str() << std::endl;
  47. assert(os.str() == "count=2 rgb=(1, 2, 3)");
  48. }
  49. //]