#ifndef STATS_HISTOGRAM_H #define STATS_HISTOGRAM_H #define WITH_DEBUG_PLOT #ifdef WITH_DEBUG_PLOT #include #include #include #endif #include namespace Stats { template class Histogram { #ifdef WITH_DEBUG_PLOT K::Gnuplot gp; K::GnuplotPlot plot; K::GnuplotPlotElementLines lines; #endif Scalar min; Scalar max; int bins; int cnt = 0; std::vector counts; public: /** ctor */ Histogram(Scalar min, Scalar max, int bins) : min(min), max(max), bins(bins) { clear(); #ifdef WITH_DEBUG_PLOT plot.add(&lines); #endif } int count() const { return cnt; } void add(const Scalar x) { const int idx = binIdx(x); counts.at(idx) += 1; ++cnt; if (cnt % 200 == 0) {showPlot();} } void clear() { counts.clear(); counts.resize(bins); cnt = 0; } #ifdef WITH_DEBUG_PLOT void showPlot() { lines.clear(); lines.add(K::GnuplotPoint2(-1,0)); for (size_t idx = 0; idx < counts.size(); ++idx) { const Scalar val = binValue(idx); const Scalar sum = counts[idx]; const K::GnuplotPoint2 gp2(val, sum); lines.add(gp2); } gp.draw(plot); gp.flush(); } #endif private: int binIdx(const Scalar val) const { return (val - min) / (max-min) * bins; } Scalar binValue(const int idx) { return idx * (max-min) + min; } }; } #endif // STATS_HISTOGRAM_H