forked from swayfreeda/ImageBasedModellingEduV1.0
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhistogram.cpp
executable file
·63 lines (53 loc) · 1.65 KB
/
histogram.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
* Copyright (C) 2015, Nils Moehrle
* TU Darmstadt - Graphics, Capture and Massively Parallel Computing
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the LICENSE.txt file for details.
*/
#include <algorithm>
#include <cassert>
#include <fstream>
#include <cstring>
#include <cerrno>
#include <math.h>
#include <util/file_system.h>
#include <util/exception.h>
#include "histogram.h"
Histogram::Histogram(float _min, float _max, std::size_t num_bins)
:min(_min), max(_max), num_values(0) {
bins.resize(num_bins);
}
void
Histogram::add_value(float value) {
float clamped_value = std::max(min, std::min(max, value));
std::size_t index = floor(((clamped_value - min) / (max - min)) * (bins.size() - 1));
assert(index < bins.size());
bins[index]++;
++num_values;
}
void
Histogram::save_to_file(std::string const & filename) const {
std::ofstream out(filename.c_str());
if (!out.good())
throw util::FileException(filename, std::strerror(errno));
out << "Bin, Values" << std::endl;
for (std::size_t i = 0; i < bins.size(); ++i) {
out << i << ", " << bins[i] << std::endl;
}
out.close();
}
float
Histogram::get_approx_percentile(float percentile) const {
assert(percentile >= 0.0f && percentile <= 1.0f);
int num = 0;
float upper_bound = min;
for (std::size_t i = 0; i < bins.size(); ++i) {
if (static_cast<float>(num) / num_values > percentile)
return upper_bound;
num += bins[i];
upper_bound = (static_cast<float>(i) / (bins.size() - 1)) * (max - min) + min;
}
return max;
}