Visual Vibration Tracking 0.2
Загрузка...
Поиск...
Не найдено
histogram.cpp
1#include "VVT-V2/histogram.h"
2
3Histogram::Histogram(int width, int height, int x_limit, int id, std::vector<double>& x_values, std::vector<float>& y_values) :
4 histogram_frame_width_{ width },
5 histogram_frame_height_{ height },
6 x_limit_{ x_limit },
7 is_histogram_plotted_{ false },
8 signature_amount_{ 8 },
9 dead_zone_coeff_{ 0.0f },
10 x_values_{ &x_values },
11 y_values_{ &y_values }
12{
13 // Инициализация гистограммы пустым кадром черного цвета
14 histogram_offset_ = static_cast<float>(histogram_frame_width_) * 0.05;
15 axis_signature_offset_ = static_cast<float>(histogram_frame_width_) * 0.03;
16 histogram_ = Mat(Size(histogram_frame_width_, histogram_frame_height_), CV_32F, Scalar(0, 0, 0));
17 // Инициализируем название окна
18 winname_ = "histogram " + std::to_string(id);
19 // Посчитаем интервал между подписями оси
20 signature_interval_ = (histogram_.cols - histogram_offset_ * 2.0) / static_cast<float>(signature_amount_ - 1);
21}
22
24{
26 destroyWindow(winname_);
27}
28
29void Histogram::OnMouse(int event, int x, int y, int flags, void* userdata)
30{
31 Histogram* d = static_cast<Histogram*>(userdata);
32 d->DetectEvent(event, x, y, flags);
33}
34
35void Histogram::DetectEvent(int event, int x, int y, int flags)
36{
37 switch (event) {
38 // ЛКМ была прожата вниз
39 case EVENT_LBUTTONDOWN:
40 {
42 destroyWindow(winname_);
43 break;
44 }
45 case EVENT_MOUSEMOVE:
46 {
49 break;
50 }
51 }
52}
53
55{
57 {
59 imshow(winname_, histogram_);
60 setMouseCallback(winname_, OnMouse, (void*)this);
61 }
62}
63
64void Histogram::SetXValues(std::vector<double> x_values)
65{
66 //x_values_ = x_values;
67}
68
69void Histogram::SetYValues(std::vector<float> y_values)
70{
71 //y_values_ = y_values;
72}
73
75{
76 // Устанавливаем флаг
78}
79
80void Histogram::SetHistogramWindowProperty(int prop_id, int prop_value)
81{
82 setWindowProperty(winname_, prop_id, prop_value);
83}
84
86{
87 Mat frame = Mat(Size(histogram_frame_width_, histogram_frame_height_), CV_32F, Scalar(0, 0, 0));
88
89 // Отрисовываем рамку гистограммы
90 rectangle(frame, Rect(
91 Point2f(histogram_offset_ * 0.5, histogram_offset_ * 0.5), // top-left
93 Scalar(255, 255, 255),
94 1
95 );
96
97 // Отрисовываем подписи
98 for (int i = 0; i < signature_amount_; i++)
99 {
100 float signature_start = static_cast<float>(x_values_->front());
101 float signature_interval = static_cast<float>(x_limit_ - signature_start) / static_cast<float>(signature_amount_ - 1);
102 float value = signature_start + signature_interval * i;
103 putText(
104 frame,
105 to_string_with_precision(value, 1),
107 FONT_HERSHEY_PLAIN,
108 1,
109 Scalar(255, 255, 255)
110 );
111 }
112
113 frame.copyTo(histogram_background_);
114}
115
117{
119 float interval = ((histogram_.cols) - histogram_offset_ * 2.0) / y_values_->size();
120
121 Mat frame = histogram_background_.clone();
122
123 // Инициализируем максимальные и минимальные значения магнитуд
124 float max_value = 0.0;
125
126 for (int i = 0; i < y_values_->size(); i++)
127 {
128 if (y_values_->at(i) > max_value)
129 max_value = y_values_->at(i);
130 }
131
132
133 // Отрисовка столбцов
134 for (int i = 0; i < y_values_->size(); i++)
135 {
136 float x_0 = histogram_offset_ + i * interval + interval;
138 float x_1 = x_0;
139 float y_1 = y_0 - y_values_->at(i) / max_value * (histogram_frame_height_ - 2 * histogram_offset_ - axis_signature_offset_);
140
141 // Если мышь указывает на текущее значение, отрисовываем это значение рядом с курсором
142 if (IsInteracted(static_cast<int>(x_0), interval))
143 {
144 PlotMouseValue(frame, i);
145 }
146 line(frame, Point2f(x_0, y_0), Point2f(x_1, y_1), Scalar(255, 255, 255), 1, LINE_AA);
147 }
148
149 return frame;
150}
151
152bool Histogram::IsInteracted(int x, int interval)
153{
154 if (interval > 1)
155 {
156 Rect interaction_box = Rect(Point2f(x - interval * 0.9, -1), Point2f(x + interval * 0.9, 1));
157 return ((interaction_box.contains(Point2i(last_mouse_coordinates_.x, 0))) ? true : false);
158 }
159 return ((last_mouse_coordinates_.x == x) ? true : false);
160}
161
162void Histogram::PlotMouseValue(Mat& frame, int value_idx)
163{
164 putText(
165 frame,
166 to_string_with_precision(x_values_->at(value_idx), 1),
168 FONT_HERSHEY_PLAIN,
169 1,
170 Scalar(255, 255, 255)
171 );
172}
173
174std::string Histogram::to_string_with_precision(const float value, const int n)
175{
176 std::ostringstream out;
177 out.precision(n);
178 out << std::fixed << value;
179 return out.str();
180}
Класс для создания объектов-гистограмм, на которые можно выводить различную информацию
Definition: histogram.h:17
std::vector< float > * y_values_
Значения гистограммы по оси Y.
Definition: histogram.h:127
Mat histogram_background_
cv::Mat фон для гистограммы
Definition: histogram.h:119
static void OnMouse(int event, int x, int y, int flags, void *userdata)
callback функция для определения события (используется для хэндлинга клика мышью)
Definition: histogram.cpp:29
int histogram_frame_width_
Ширина окна гистограммы (включая оффсет)
Definition: histogram.h:107
int histogram_frame_height_
Высота окна гистограммы (включая оффсет)
Definition: histogram.h:111
std::vector< double > * x_values_
Значения гистограммы по оси X.
Definition: histogram.h:123
Point2i last_mouse_coordinates_
Координаты мыши (курсора)
Definition: histogram.h:147
bool IsInteracted(int x, int interval)
Проверяет, соответствует ли точка координате мыши
Definition: histogram.cpp:152
std::string winname_
Название окна
Definition: histogram.h:99
Histogram(int width, int height, int x_limit, int id, std::vector< double > &x_values, std::vector< float > &y_values)
Конструктор этого класса
Definition: histogram.cpp:3
void PlotMouseValue(Mat &frame, int value_idx)
Выводит значение частоты рядом с курсором
Definition: histogram.cpp:162
float histogram_offset_
Оффсет рамки гистограммы
Definition: histogram.h:103
void ShowHistogram()
Выводит гистограмму в окно гистограммы
Definition: histogram.cpp:54
Mat histogram_
cv::Mat изображение гистограммы
Definition: histogram.h:115
void SetHistogramWindowProperty(int prop_id, int prop_value)
Обновляет статус окна гистограммы (например, для вывода на передний план)
Definition: histogram.cpp:80
Mat CalcHistogram()
Вычисляет значения для гистограммы
Definition: histogram.cpp:116
std::string to_string_with_precision(const float value, const int n=6)
Для ограничения кол-ва знаков
Definition: histogram.cpp:174
void SetYValues(std::vector< float > y_values)
Устанавливает Y-ы
Definition: histogram.cpp:69
float signature_interval_
Интервал для делений оси и количество этих делений
Definition: histogram.h:135
void SetXValues(std::vector< double > x_values)
Устанавливает X-ы
Definition: histogram.cpp:64
void DetectEvent(int event, int x, int y, int flags)
callback функция для определения события (используется для хэндлинга клика мышью)
Definition: histogram.cpp:35
void SetHistogramFlag(bool flag)
Устанавливает статус флага отрисовки гистограммы
Definition: histogram.cpp:74
~Histogram()
Деструктор этого класса
Definition: histogram.cpp:23
int signature_amount_
Количество подписей на оси
Definition: histogram.h:139
bool is_histogram_plotted_
Флаг для отрисовки гистограммы
Definition: histogram.h:93
int x_limit_
Максимальное (предельное) значение по оси X.
Definition: histogram.h:143
float axis_signature_offset_
Отступ для подписей оси
Definition: histogram.h:131
void InitHistogramBackground()
Подгатавливаем Histogram::histogram_background_ для дальнейшего использования
Definition: histogram.cpp:85