Visual Vibration Tracking 0.2
Загрузка...
Поиск...
Не найдено
contour_handler.cpp
1#include <VVT-V2/contour_handler.h>
2
3ContourHandler::ContourHandler(Mat frame, Rect* ROI) :
4 minimal_distance_{ 5.0f }
5{
6 Mat prep_frame;
7 std::vector<Vec4i> hierarchy = { 0 };
8
9 // Проверка на то, был ли послан ROI или нет
10 if (ROI != nullptr)
11 prep_frame = Mat(frame, *ROI);
12 else
13 frame.copyTo(prep_frame);
14
15 // Проверка на грейскейл
16 if (frame.channels() > 2)
17 cvtColor(prep_frame, prep_frame, COLOR_BGR2GRAY);
18
19 // Имаге процессинг
20 GaussianBlur(prep_frame, prep_frame, Size(7, 7), 0);
21 threshold(prep_frame, prep_frame, 80, 255, cv::THRESH_BINARY);
22 Canny(prep_frame, prep_frame, 64, 192);
23 Canny(prep_frame, prep_frame, 64, 192);
24
25 // Находим контуры и дополнительно, если ROI не пустой
26 // транслируем координаты из координат "ROI-куска" в координаты исходного изображения (аналог contour_shapes_[i][j] += ROI.tl())
27 if (ROI != nullptr)
28 findContours(prep_frame, contour_shapes_, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, ROI->tl());
29 else
30 findContours(prep_frame, contour_shapes_, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
31}
32
34{
35 for (int i = 0; i < contour_shapes_.size(); i++)
36 {
37 drawContours(frame, contour_shapes_, i, Scalar(255, 0, 0), 6);
38 }
39}
40
41std::vector<std::vector<Point2i>> ContourHandler::GetContours()
42{
43 return contour_shapes_;
44}
45
47{
48 std::vector<Point2f> continous_contour_shapes;
49
50 // Проходимся по вектору контуров (std::vector<std::vector>>) и проверяем на соответствие условию ниже
51 auto extern_itt = contour_shapes_.begin();
52 while (extern_itt != contour_shapes_.end())
53 {
54 std::vector<Point> shape = *extern_itt;
55
56 auto intern_itt = shape.begin();
57 while (intern_itt != shape.end())
58 {
59 // То самое условие: минимальная дистанция между точками + размер контура
60 if (CalculateDistance(*intern_itt, *(intern_itt + 1)) > minimal_distance_ && (contourArea(*extern_itt) > 100))
61 {
62 continous_contour_shapes.push_back(*intern_itt);
63 }
64 intern_itt++;
65 }
66
67 extern_itt++;
68 }
69
70 // Ограничиваем длину контуров
71 while (continous_contour_shapes.size() > 500)
72 continous_contour_shapes = MakeTwiceThinner(continous_contour_shapes);
73
74 return continous_contour_shapes;
75}
76
77template<typename T>
78std::vector<T> ContourHandler::MakeTwiceThinner(std::vector<T> src)
79{
80 std::vector<T> dst;
81
82 auto it = src.begin();
83 while (it != src.end() - 1)
84 {
85 if ((std::distance(src.begin(), it)) % 2 == 0)
86 dst.push_back(*(it));
87 it++;
88 }
89
90 return dst;
91}
92
93template<typename T>
94float ContourHandler::CalculateDistance(T point1, T point2)
95{
96 return sqrt((point1.x - point2.x) * (point1.x - point2.x) + (point1.y - point2.y) * (point1.y - point2.y));
97}
float minimal_distance_
Минимальное расстояние между точками контура, при котором "левая" ("первая") точка будет сохранена
ContourHandler(Mat frame, Rect *ROI=nullptr)
Конструктор этого класса
std::vector< std::vector< Point2i > > GetContours()
Возвращает найденные контура в виде { { contour_1 }, { contour_2 }, ... , { contour_n } }.
void DrawContours(Mat &frame)
Отрисовывает контура на изображении
std::vector< Point2f > GetContinousContours()
Возвращает найденные контура в виде { contour_1, contour_2, ... , contour_n }.
float CalculateDistance(T point1, T point2)
Вычисляет расстояние между двумя точками
std::vector< T > MakeTwiceThinner(std::vector< T > src)
Удаляет каждый второй элемент вектора (уменьшает размер в два раза)
std::vector< std::vector< Point > > contour_shapes_
Контуры в виде { { contour_1 }, { contour_2 }, ... , { contour_n } }.