Visual Vibration Tracking 0.2
Загрузка...
Поиск...
Не найдено
Открытые члены | Закрытые члены | Закрытые данные | Полный список членов класса
Класс VideoUndistorter

Класс для удаления дисторсии на видео Подробнее...

#include <video_undistorter.h>

Открытые члены

 VideoUndistorter (std::string input_file_name_, std::string output_file_name, std::string txt_file_name)
 Конструктор этого класса Подробнее...
 
int ExecuteVideoUndistortion ()
 Основная часть. Выполняет удаление дисторсии из видео Подробнее...
 

Закрытые члены

void AddTips (Mat &frame, std::string tip)
 По аналогии с FrameHandler::AddTips добавляет подсказки пользователя. В данном случае это - номер текущего обрабатываемого кадра и общее кол-во кадров.
. Подробнее...
 
void SaveFrame (Mat frame)
 Сохраняет кадр в выходную последовательность (видео) Подробнее...
 
void LoadFoundParamsFromFile (std::string txt_file_name)
 Загружает параметры (коэффициенты fx, fy, cx, cy), необходимые для удаления дисторсии. Были найдены в CameraCalibrator. Подробнее...
 
std::vector< std::string > SplitString (std::string line, std::string delimiter)
 Разделяет строку на некоторое количество подстрок по специальному символу - разделителю Подробнее...
 

Закрытые данные

std::string winname_
 Название главного окна Подробнее...
 
VideoCapture * input_cap_
 "Поток" из кадров входного видео (последовательности) Подробнее...
 
VideoWriter * output_cap_
 "Поток" из кадров выходного видео (последовательности) Подробнее...
 
double frame_width_
 Ширина кадра (входного и выходного) Подробнее...
 
double frame_height_
 Ширина кадра (входного и выходного) Подробнее...
 
double frame_count_
 Количество кадров входного видео Подробнее...
 
double fps_
 ФПС входного видео Подробнее...
 
std::string input_file_name_
 Путь к входному видео Подробнее...
 
std::string output_file_name_
 Путь к выходному видео Подробнее...
 
Mat camera_matrix_
 Та самая матрица, присущая конкретной паре - линща + камера. Подробнее...
 
Mat distortion_coefficients_
 Коэффициенты дисторсии Подробнее...
 
Mat current_frame_
 Текущий кадр с дисторсией Подробнее...
 
Mat undistorted_frame_
 Текущий кадр с удалённой дисторсией Подробнее...
 
double fx_
 Коэффициент матрицы VideoUndistorter::camera_matrix_. Подробнее...
 
double fy_
 Коэффициент матрицы VideoUndistorter::camera_matrix_. Подробнее...
 
double px_
 Коэффициент матрицы VideoUndistorter::camera_matrix_. Подробнее...
 
double py_
 Коэффициент матрицы VideoUndistorter::camera_matrix_. Подробнее...
 
std::string txt_file_name_
 Путь к файлу с коэффициентами Подробнее...
 

Подробное описание

Класс для удаления дисторсии на видео

Объект класса осуществляет чтение и сохранение кадров с удаленной дисторсией в выходную последовательность (видео)

Необходимо сделать:
Работу с кадрами (чтение, грейскейл) следует выполнять с помощью FrameHandler. На данный момент это происходит не так. Внутри этого класса своя реализация чтения видео.
cv::VideoCapture способно считывать любую последовательность изображений, не обязательно видео, можно и набор изображений по какому-то пути (из папки, например).
Это не успел сделать

См. определение в файле video_undistorter.h строка 30

Конструктор(ы)

◆ VideoUndistorter()

VideoUndistorter::VideoUndistorter ( std::string  input_file_name_,
std::string  output_file_name,
std::string  txt_file_name 
)

Конструктор этого класса

Аргументы
input_file_nameимя (путь) входного видео для обработки
output_file_nameимя (путь) выходдного видео после обработки
txt_file_nameимя (путь) файла с "коэффициентами дисторсии" линзы
Заметки
CameraCalibrator

См. определение в файле video_undistorter.cpp строка 3

3 :
4 input_file_name_{ input_file_name },
5 output_file_name_{ output_file_name },
6 txt_file_name_{ txt_file_name },
7 winname_{ "Undistortion" }
8{
9 input_cap_ = new VideoCapture(input_file_name);
10
11 frame_width_ = input_cap_->get(CAP_PROP_FRAME_WIDTH);
12 frame_height_ = input_cap_->get(CAP_PROP_FRAME_HEIGHT);
13 frame_count_ = input_cap_->get(CAP_PROP_FRAME_COUNT);
14 fps_ = input_cap_->get(CAP_PROP_FPS);
15
16 output_cap_ = new VideoWriter
17 (
19 cv::VideoWriter::fourcc('m', 'p', '4', 'v'), // codec
20 fps_,
22 );
23
24 namedWindow(winname_, WINDOW_NORMAL);
25}
double frame_height_
Ширина кадра (входного и выходного)
VideoCapture * input_cap_
"Поток" из кадров входного видео (последовательности)
double frame_width_
Ширина кадра (входного и выходного)
double fps_
ФПС входного видео
std::string input_file_name_
Путь к входному видео
double frame_count_
Количество кадров входного видео
VideoWriter * output_cap_
"Поток" из кадров выходного видео (последовательности)
std::string winname_
Название главного окна
std::string output_file_name_
Путь к выходному видео
std::string txt_file_name_
Путь к файлу с коэффициентами

◆ ~VideoUndistorter()

VideoUndistorter::~VideoUndistorter ( )

См. определение в файле video_undistorter.cpp строка 27

28{
29 input_cap_->release();
30 output_cap_->release();
31
32 delete input_cap_;
33 delete output_cap_;
34
35 destroyWindow(winname_);
36}

Методы

◆ AddTips()

void VideoUndistorter::AddTips ( Mat &  frame,
std::string  tip 
)
private

По аналогии с FrameHandler::AddTips добавляет подсказки пользователя. В данном случае это - номер текущего обрабатываемого кадра и общее кол-во кадров.
.

Аргументы
frameкадр, на который будут добавлены подсказки
tipстрока с подсказкой
Необходимо сделать:
Вынести её в какой-то отдельный модуль, чтобы не было дублирования кода

См. определение в файле video_undistorter.cpp строка 86

87{
88 int font = FONT_HERSHEY_PLAIN;
89 double font_scale = 1.5;
90 int thickness = 2;
91
92 putText(
93 frame,
94 tip,
95 Point(frame.cols * 0.05, frame.rows * 0.05),
96 font,
97 font_scale,
98 Scalar(0, 255, 0),
99 thickness
100 );
101}

◆ ExecuteVideoUndistortion()

int VideoUndistorter::ExecuteVideoUndistortion ( )

Основная часть. Выполняет удаление дисторсии из видео

Возвращает
0 - в случае выхода из программы (смотри тело функции). 1 - в противном
Необходимо сделать:
Лучше переделать такую логику)

См. определение в файле video_undistorter.cpp строка 38

39{
40 // read distortion parameters from txt file
42
43 std::cout << frame_count_ << std::endl;
44
45 int frame_num = 0;
46 Mat mapX, mapY;
47 initUndistortRectifyMap(camera_matrix_, distortion_coefficients_, Matx33f::eye(), camera_matrix_, Size(frame_width_, frame_height_), CV_32FC1, mapX, mapY);
48 //undistort each frame in loop
49 while (input_cap_->get(CAP_PROP_POS_FRAMES) < frame_count_)
50 {
52 if (!current_frame_.empty())
53 {
54 std::cout << "Processing frame " << input_cap_->get(CAP_PROP_POS_FRAMES) << "/" << frame_count_ << std::endl;
55 //imshow(winname_, current_frame_);
56
57 //undistort(current_frame_, undistorted_frame_, camera_matrix_, distortion_coefficients_);
58 remap(current_frame_, undistorted_frame_, mapX, mapY, INTER_LINEAR);
62
63 int code = waitKey(20);
64 switch (code)
65 {
66 // Пауза
67 // Клавиши - пробел (ASCII code)
68 case 32:
69 {
70 waitKey(0);
71 break;
72 }
73 case 'q':
74 {
75 return 0;
76 break;
77 }
78 }
79 }
80 }
81
82 std::cout << "Undistortion completed" << std::endl;
83 return 1;
84}
void AddTips(Mat &frame, std::string tip)
По аналогии с FrameHandler::AddTips добавляет подсказки пользователя. В данном случае это - номер тек...
Mat current_frame_
Текущий кадр с дисторсией
Mat camera_matrix_
Та самая матрица, присущая конкретной паре - линща + камера.
Mat distortion_coefficients_
Коэффициенты дисторсии
void SaveFrame(Mat frame)
Сохраняет кадр в выходную последовательность (видео)
void LoadFoundParamsFromFile(std::string txt_file_name)
Загружает параметры (коэффициенты fx, fy, cx, cy), необходимые для удаления дисторсии....
Mat undistorted_frame_
Текущий кадр с удалённой дисторсией
std::string ToStringWithPrecision(const T value, const int n=9)
Выполняет округление числа с определенной точностью
Definition: helper.h:49

◆ LoadFoundParamsFromFile()

void VideoUndistorter::LoadFoundParamsFromFile ( std::string  txt_file_name)
private

Загружает параметры (коэффициенты fx, fy, cx, cy), необходимые для удаления дисторсии. Были найдены в CameraCalibrator.

Аргументы
txt_file_nameпуть к файлу с коэффициентами

См. определение в файле video_undistorter.cpp строка 108

109{
110
111 std::vector<double> dist;
112
113 std::ifstream file;
114 std::string line;
115 std::vector<std::vector<double>> read_data;
116
117 file.open(txt_file_name);
118 if (file.is_open())
119 {
120 std::cout << "Param file opened" << std::endl;
121
122 while (!file.eof())
123 {
124 file >> line;
125 std::vector<std::string> delimited_line = SplitString(line, ";");
126 delimited_line.erase(delimited_line.begin());
127
128 std::vector<double> data;
129
130 for (int i = 0; i < delimited_line.size(); i++)
131 {
132 data.push_back(std::stod(delimited_line[i]));
133 }
134 read_data.push_back(data);
135 }
136
137 file.close();
138 }
139
140 fx_ = read_data[0][0];
141 fy_ = read_data[1][0];
142 px_ = read_data[2][0];
143 py_ = read_data[3][0];
144 dist = { read_data[4][0], read_data[4][1], read_data[4][2], read_data[4][3], read_data[4][4] };
145
146 std::vector<double> intrin_arr = { fx_, 0, px_, 0, fy_, py_, 0, 0, 1 };
147
148 camera_matrix_ = Mat(3, 3, CV_64F, intrin_arr.data());
149 distortion_coefficients_ = Mat(1, dist.size(), CV_64F, dist.data());
150
151 std::cout << camera_matrix_.size() << std::endl;
152 std::cout << distortion_coefficients_.size() << std::endl;
153 std::cout << camera_matrix_ << std::endl;
154 std::cout << distortion_coefficients_ << std::endl;
155}
double fy_
Коэффициент матрицы VideoUndistorter::camera_matrix_.
double px_
Коэффициент матрицы VideoUndistorter::camera_matrix_.
double py_
Коэффициент матрицы VideoUndistorter::camera_matrix_.
double fx_
Коэффициент матрицы VideoUndistorter::camera_matrix_.
std::vector< std::string > SplitString(std::string line, std::string delimiter)
Разделяет строку на некоторое количество подстрок по специальному символу - разделителю

◆ SaveFrame()

void VideoUndistorter::SaveFrame ( Mat  frame)
private

Сохраняет кадр в выходную последовательность (видео)

Аргументы
frameкадр, который будет сохранён
Необходимо сделать:
Предложения по улучшению описаны описании класса (VideoUndistorter)

См. определение в файле video_undistorter.cpp строка 103

104{
105 output_cap_->write(frame);
106}

◆ SplitString()

std::vector< std::string > VideoUndistorter::SplitString ( std::string  line,
std::string  delimiter 
)
private

Разделяет строку на некоторое количество подстрок по специальному символу - разделителю

Аргументы
input_stringисходная строка
delimiterразделитель, по которому исходная строка будет разделена
Возвращает
Вектор, состоящий из разделенных частей исходной строки (вектор из векторов)

См. определение в файле video_undistorter.cpp строка 157

158{
159 int start_position = 0;
160 int end_position;
161 int delimiter_length = delimiter.length();
162
163 std::string token;
164 std::vector<std::string> left;
165
166 while ((end_position = input_string.find(delimiter, start_position)) != std::string::npos) {
167 token = input_string.substr(start_position, end_position - start_position);
168 start_position = end_position + delimiter_length;
169 left.push_back(token);
170 }
171
172 left.push_back(input_string.substr(start_position));
173 return left;
174}

Данные класса

◆ camera_matrix_

Mat VideoUndistorter::camera_matrix_
private

Та самая матрица, присущая конкретной паре - линща + камера.

См. также
CameraCalibrator

См. определение в файле video_undistorter.h строка 117

◆ current_frame_

Mat VideoUndistorter::current_frame_
private

Текущий кадр с дисторсией

См. определение в файле video_undistorter.h строка 125

◆ distortion_coefficients_

Mat VideoUndistorter::distortion_coefficients_
private

Коэффициенты дисторсии

Заметки
CameraCalibrator

См. определение в файле video_undistorter.h строка 121

◆ fps_

double VideoUndistorter::fps_
private

ФПС входного видео

См. определение в файле video_undistorter.h строка 104

◆ frame_count_

double VideoUndistorter::frame_count_
private

Количество кадров входного видео

См. определение в файле video_undistorter.h строка 100

◆ frame_height_

double VideoUndistorter::frame_height_
private

Ширина кадра (входного и выходного)

См. определение в файле video_undistorter.h строка 96

◆ frame_width_

double VideoUndistorter::frame_width_
private

Ширина кадра (входного и выходного)

См. определение в файле video_undistorter.h строка 92

◆ fx_

double VideoUndistorter::fx_
private

Коэффициент матрицы VideoUndistorter::camera_matrix_.

См. также
CameraCalibrator

См. определение в файле video_undistorter.h строка 134

◆ fy_

double VideoUndistorter::fy_
private

Коэффициент матрицы VideoUndistorter::camera_matrix_.

См. также
CameraCalibrator

См. определение в файле video_undistorter.h строка 139

◆ input_cap_

VideoCapture* VideoUndistorter::input_cap_
private

"Поток" из кадров входного видео (последовательности)

См. определение в файле video_undistorter.h строка 84

◆ input_file_name_

std::string VideoUndistorter::input_file_name_
private

Путь к входному видео

См. определение в файле video_undistorter.h строка 108

◆ output_cap_

VideoWriter* VideoUndistorter::output_cap_
private

"Поток" из кадров выходного видео (последовательности)

См. определение в файле video_undistorter.h строка 88

◆ output_file_name_

std::string VideoUndistorter::output_file_name_
private

Путь к выходному видео

См. определение в файле video_undistorter.h строка 112

◆ px_

double VideoUndistorter::px_
private

Коэффициент матрицы VideoUndistorter::camera_matrix_.

См. также
CameraCalibrator

См. определение в файле video_undistorter.h строка 144

◆ py_

double VideoUndistorter::py_
private

Коэффициент матрицы VideoUndistorter::camera_matrix_.

См. также
CameraCalibrator

См. определение в файле video_undistorter.h строка 149

◆ txt_file_name_

std::string VideoUndistorter::txt_file_name_
private

Путь к файлу с коэффициентами

См. также
CameraCalibrator

См. определение в файле video_undistorter.h строка 154

◆ undistorted_frame_

Mat VideoUndistorter::undistorted_frame_
private

Текущий кадр с удалённой дисторсией

См. определение в файле video_undistorter.h строка 129

◆ winname_

std::string VideoUndistorter::winname_
private

Название главного окна

См. определение в файле video_undistorter.h строка 80


Объявления и описания членов классов находятся в файлах: