blob: 10062ba1b39ff9e94280e10e82b3bd9686404dbf [file] [log] [blame]
James Kuszmaul7e958812023-02-11 15:34:31 -08001#ifndef FRC971_VISION_CALIBRATION_LIB_H_
2#define FRC971_VISION_CALIBRATION_LIB_H_
3#include <cmath>
4#include <opencv2/calib3d.hpp>
5#include <opencv2/highgui/highgui.hpp>
6#include <opencv2/imgproc.hpp>
7#include <regex>
8
9#include "Eigen/Dense"
10#include "Eigen/Geometry"
11#include "absl/strings/str_format.h"
12#include "aos/events/event_loop.h"
13#include "aos/network/team_number.h"
14#include "aos/time/time.h"
15#include "aos/util/file.h"
16#include "frc971/vision/charuco_lib.h"
17
18namespace frc971 {
19namespace vision {
20
21class IntrinsicsCalibration {
22 public:
23 IntrinsicsCalibration(aos::EventLoop *event_loop, std::string_view pi,
24 std::string_view camera_id,
25 std::string_view base_intrinsics_file,
26 bool display_undistorted,
27 std::string_view calibration_folder,
28 aos::ExitHandle *exit_handle);
29
30 void HandleCharuco(cv::Mat rgb_image,
31 const aos::monotonic_clock::time_point /*eof*/,
32 std::vector<cv::Vec4i> charuco_ids,
33 std::vector<std::vector<cv::Point2f>> charuco_corners,
34 bool valid, std::vector<Eigen::Vector3d> rvecs_eigen,
35 std::vector<Eigen::Vector3d> tvecs_eigen);
36
37 void MaybeCalibrate();
38
39 static aos::FlatbufferDetachedBuffer<calibration::CameraCalibration>
40 BuildCalibration(cv::Mat camera_matrix, cv::Mat dist_coeffs,
41 aos::realtime_clock::time_point realtime_now, int pi_number,
42 std::string_view camera_id, uint16_t team_number);
43
44 private:
45 static constexpr double kDeltaRThreshold = M_PI / 6.0;
46 static constexpr double kDeltaTThreshold = 0.3;
47
48 static constexpr double kFrameDeltaRLimit = M_PI / 60;
49 static constexpr double kFrameDeltaTLimit = 0.01;
50
51 std::string pi_;
52 const std::optional<uint16_t> pi_number_;
53 const std::string camera_id_;
54
55 std::vector<std::vector<int>> all_charuco_ids_;
56 std::vector<std::vector<cv::Point2f>> all_charuco_corners_;
57
58 Eigen::Affine3d H_camera_board_;
59 Eigen::Affine3d prev_H_camera_board_;
60 Eigen::Affine3d prev_image_H_camera_board_;
61
62 // Camera intrinsics that we will use to bootstrap the intrinsics estimation
63 // here. We make use of the intrinsics in this calibration to allow us to
64 // estimate the relative pose of the charuco board and then identify how much
65 // the board is moving.
66 aos::FlatbufferDetachedBuffer<calibration::CameraCalibration>
67 base_intrinsics_;
68 CharucoExtractor charuco_extractor_;
69 ImageCallback image_callback_;
70
71 const bool display_undistorted_;
72 const std::string calibration_folder_;
73 aos::ExitHandle *exit_handle_;
74};
75
76} // namespace vision
77} // namespace frc971
78#endif // FRC971_VISION_CALIBRATION_LIB_H_