blob: 9293d505554901f14b3d6e850da4d5c2b92c4555 [file] [log] [blame]
Yash Chainani5c005da2022-01-22 16:51:11 -08001#include <cmath>
Austin Schuhc1f118e2020-04-11 15:50:08 -07002#include <opencv2/calib3d.hpp>
Austin Schuhc1f118e2020-04-11 15:50:08 -07003#include <opencv2/highgui/highgui.hpp>
4#include <opencv2/imgproc.hpp>
Jim Ostrowskifec0c332022-02-06 23:28:26 -08005#include <regex>
Austin Schuhc1f118e2020-04-11 15:50:08 -07006
Yash Chainani5c005da2022-01-22 16:51:11 -08007#include "Eigen/Dense"
8#include "Eigen/Geometry"
Austin Schuhc1f118e2020-04-11 15:50:08 -07009#include "absl/strings/str_format.h"
10#include "aos/events/shm_event_loop.h"
11#include "aos/init.h"
12#include "aos/network/team_number.h"
13#include "aos/time/time.h"
14#include "aos/util/file.h"
Yash Chainani5c005da2022-01-22 16:51:11 -080015#include "y2020/vision/charuco_lib.h"
Austin Schuhc1f118e2020-04-11 15:50:08 -070016
Yash Chainani5c005da2022-01-22 16:51:11 -080017DEFINE_string(calibration_folder, ".", "Folder to place calibration files.");
Jim Ostrowskifec0c332022-02-06 23:28:26 -080018DEFINE_string(camera_id, "", "Camera ID in format YY-NN-- year and number.");
19DEFINE_string(config, "config.json", "Path to the config file to use.");
Austin Schuhc1f118e2020-04-11 15:50:08 -070020DEFINE_bool(display_undistorted, false,
21 "If true, display the undistorted image.");
Jim Ostrowskifec0c332022-02-06 23:28:26 -080022DEFINE_string(pi, "", "Pi name to calibrate.");
Austin Schuhc1f118e2020-04-11 15:50:08 -070023
24namespace frc971 {
25namespace vision {
26
Austin Schuh25837f22021-06-27 15:49:14 -070027class Calibration {
Austin Schuhc1f118e2020-04-11 15:50:08 -070028 public:
Jim Ostrowskifec0c332022-02-06 23:28:26 -080029 Calibration(aos::ShmEventLoop *event_loop, std::string_view pi,
30 std::string_view camera_id)
Austin Schuh25837f22021-06-27 15:49:14 -070031 : event_loop_(event_loop),
32 pi_(pi),
33 pi_number_(aos::network::ParsePiNumber(pi)),
Jim Ostrowskifec0c332022-02-06 23:28:26 -080034 camera_id_(camera_id),
Yash Chainani460c9fb2022-02-12 18:14:50 -080035 H_camera_board_(Eigen::Affine3d()),
36 prev_H_camera_board_(Eigen::Affine3d()),
Austin Schuh25837f22021-06-27 15:49:14 -070037 charuco_extractor_(
38 event_loop, pi,
Yash Chainani5c005da2022-01-22 16:51:11 -080039 [this](cv::Mat rgb_image,
40 const aos::monotonic_clock::time_point eof,
Austin Schuh25837f22021-06-27 15:49:14 -070041 std::vector<int> charuco_ids,
42 std::vector<cv::Point2f> charuco_corners, bool valid,
43 Eigen::Vector3d rvec_eigen, Eigen::Vector3d tvec_eigen) {
Jim Ostrowskifec0c332022-02-06 23:28:26 -080044 HandleCharuco(rgb_image, eof, charuco_ids, charuco_corners, valid,
45 rvec_eigen, tvec_eigen);
Austin Schuh25837f22021-06-27 15:49:14 -070046 }) {
47 CHECK(pi_number_) << ": Invalid pi number " << pi
48 << ", failed to parse pi number";
Jim Ostrowskifec0c332022-02-06 23:28:26 -080049 std::regex re{"^[0-9][0-9]-[0-9][0-9]"};
50 CHECK(std::regex_match(camera_id_, re))
51 << ": Invalid camera_id '" << camera_id_
52 << "', should be of form YY-NN";
Austin Schuhc1f118e2020-04-11 15:50:08 -070053 }
54
Austin Schuhea7b0142021-10-08 22:04:53 -070055 void HandleCharuco(cv::Mat rgb_image,
56 const aos::monotonic_clock::time_point /*eof*/,
Austin Schuh25837f22021-06-27 15:49:14 -070057 std::vector<int> charuco_ids,
58 std::vector<cv::Point2f> charuco_corners, bool valid,
Yash Chainani5c005da2022-01-22 16:51:11 -080059 Eigen::Vector3d rvec_eigen, Eigen::Vector3d tvec_eigen) {
60 // Reduce resolution displayed on remote viewer to prevent lag
61 cv::resize(rgb_image, rgb_image,
62 cv::Size(rgb_image.cols / 2, rgb_image.rows / 2));
Ravago Jonescf453ab2020-05-06 21:14:53 -070063 cv::imshow("Display", rgb_image);
Austin Schuhc1f118e2020-04-11 15:50:08 -070064
Ravago Jonescf453ab2020-05-06 21:14:53 -070065 if (FLAGS_display_undistorted) {
Austin Schuh25837f22021-06-27 15:49:14 -070066 const cv::Size image_size(rgb_image.cols, rgb_image.rows);
Ravago Jonescf453ab2020-05-06 21:14:53 -070067 cv::Mat undistorted_rgb_image(image_size, CV_8UC3);
Austin Schuh25837f22021-06-27 15:49:14 -070068 cv::undistort(rgb_image, undistorted_rgb_image,
69 charuco_extractor_.camera_matrix(),
70 charuco_extractor_.dist_coeffs());
Austin Schuhc1f118e2020-04-11 15:50:08 -070071
Ravago Jonescf453ab2020-05-06 21:14:53 -070072 cv::imshow("Display undist", undistorted_rgb_image);
73 }
Austin Schuhc1f118e2020-04-11 15:50:08 -070074
Yash Chainani5c005da2022-01-22 16:51:11 -080075 // Calibration calculates rotation and translation delta from last image
76 // captured to automatically capture next image
77
Yash Chainani460c9fb2022-02-12 18:14:50 -080078 Eigen::Affine3d H_board_camera =
79 Eigen::Translation3d(tvec_eigen) *
80 Eigen::AngleAxisd(rvec_eigen.norm(), rvec_eigen / rvec_eigen.norm());
81 H_camera_board_ = H_board_camera.inverse();
82 Eigen::Affine3d H_delta = H_board_camera * prev_H_camera_board_;
Yash Chainani5c005da2022-01-22 16:51:11 -080083
Yash Chainani460c9fb2022-02-12 18:14:50 -080084 Eigen::AngleAxisd delta_r = Eigen::AngleAxisd(H_delta.rotation());
Yash Chainani5c005da2022-01-22 16:51:11 -080085
Yash Chainani460c9fb2022-02-12 18:14:50 -080086 Eigen::Vector3d delta_t = H_delta.translation();
Yash Chainani5c005da2022-01-22 16:51:11 -080087
88 double r_norm = std::abs(delta_r.angle());
89 double t_norm = delta_t.norm();
90
Ravago Jonescf453ab2020-05-06 21:14:53 -070091 int keystroke = cv::waitKey(1);
Yash Chainani5c005da2022-01-22 16:51:11 -080092 if (r_norm > kDeltaRThreshold || t_norm > kDeltaTThreshold) {
Austin Schuh25837f22021-06-27 15:49:14 -070093 if (valid) {
Yash Chainani460c9fb2022-02-12 18:14:50 -080094 prev_H_camera_board_ = H_camera_board_;
Yash Chainani5c005da2022-01-22 16:51:11 -080095
Austin Schuh25837f22021-06-27 15:49:14 -070096 all_charuco_ids_.emplace_back(std::move(charuco_ids));
97 all_charuco_corners_.emplace_back(std::move(charuco_corners));
Yash Chainani5c005da2022-01-22 16:51:11 -080098
99 if (r_norm > kDeltaRThreshold) {
100 LOG(INFO) << "Triggered by rotation delta = " << r_norm << " > "
101 << kDeltaRThreshold;
102 }
103 if (t_norm > kDeltaTThreshold) {
104 LOG(INFO) << "Trigerred by translation delta = " << t_norm << " > "
105 << kDeltaTThreshold;
106 }
107
108 LOG(INFO) << "Image count " << all_charuco_corners_.size();
Ravago Jonescf453ab2020-05-06 21:14:53 -0700109 }
Austin Schuhc1f118e2020-04-11 15:50:08 -0700110
Austin Schuh25837f22021-06-27 15:49:14 -0700111 if (all_charuco_ids_.size() >= 50) {
Ravago Jonescf453ab2020-05-06 21:14:53 -0700112 LOG(INFO) << "Got enough images to calibrate";
Austin Schuh25837f22021-06-27 15:49:14 -0700113 event_loop_->Exit();
Ravago Jonescf453ab2020-05-06 21:14:53 -0700114 }
115 } else if ((keystroke & 0xFF) == static_cast<int>('q')) {
Austin Schuh25837f22021-06-27 15:49:14 -0700116 event_loop_->Exit();
Ravago Jonescf453ab2020-05-06 21:14:53 -0700117 }
Austin Schuh25837f22021-06-27 15:49:14 -0700118 }
119
120 void MaybeCalibrate() {
121 if (all_charuco_ids_.size() >= 50) {
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800122 LOG(INFO) << "Beginning calibration on " << all_charuco_ids_.size()
123 << " images";
Austin Schuh25837f22021-06-27 15:49:14 -0700124 cv::Mat cameraMatrix, distCoeffs;
125 std::vector<cv::Mat> rvecs, tvecs;
126 cv::Mat stdDeviationsIntrinsics, stdDeviationsExtrinsics, perViewErrors;
127
128 // Set calibration flags (same as in calibrateCamera() function)
129 int calibration_flags = 0;
130 cv::Size img_size(640, 480);
131 const double reprojection_error = cv::aruco::calibrateCameraCharuco(
132 all_charuco_corners_, all_charuco_ids_, charuco_extractor_.board(),
133 img_size, cameraMatrix, distCoeffs, rvecs, tvecs,
134 stdDeviationsIntrinsics, stdDeviationsExtrinsics, perViewErrors,
135 calibration_flags);
136 CHECK_LE(reprojection_error, 1.0) << ": Reproduction error is bad.";
137 LOG(INFO) << "Reprojection Error is " << reprojection_error;
138
139 flatbuffers::FlatBufferBuilder fbb;
140 flatbuffers::Offset<flatbuffers::String> name_offset =
141 fbb.CreateString(absl::StrFormat("pi%d", pi_number_.value()));
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800142 flatbuffers::Offset<flatbuffers::String> camera_id_offset =
143 fbb.CreateString(camera_id_);
Austin Schuh25837f22021-06-27 15:49:14 -0700144 flatbuffers::Offset<flatbuffers::Vector<float>> intrinsics_offset =
145 fbb.CreateVector<float>(9u, [&cameraMatrix](size_t i) {
146 return static_cast<float>(
147 reinterpret_cast<double *>(cameraMatrix.data)[i]);
148 });
149
150 flatbuffers::Offset<flatbuffers::Vector<float>>
151 distortion_coefficients_offset =
152 fbb.CreateVector<float>(5u, [&distCoeffs](size_t i) {
153 return static_cast<float>(
154 reinterpret_cast<double *>(distCoeffs.data)[i]);
155 });
156
157 sift::CameraCalibration::Builder camera_calibration_builder(fbb);
158 std::optional<uint16_t> team_number =
159 aos::network::team_number_internal::ParsePiTeamNumber(pi_);
160 CHECK(team_number) << ": Invalid pi hostname " << pi_
161 << ", failed to parse team number";
162
163 const aos::realtime_clock::time_point realtime_now =
164 aos::realtime_clock::now();
165 camera_calibration_builder.add_node_name(name_offset);
166 camera_calibration_builder.add_team_number(team_number.value());
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800167 camera_calibration_builder.add_camera_id(camera_id_offset);
Austin Schuh25837f22021-06-27 15:49:14 -0700168 camera_calibration_builder.add_calibration_timestamp(
169 realtime_now.time_since_epoch().count());
170 camera_calibration_builder.add_intrinsics(intrinsics_offset);
171 camera_calibration_builder.add_dist_coeffs(
172 distortion_coefficients_offset);
173 fbb.Finish(camera_calibration_builder.Finish());
174
175 aos::FlatbufferDetachedBuffer<sift::CameraCalibration> camera_calibration(
176 fbb.Release());
177 std::stringstream time_ss;
178 time_ss << realtime_now;
179
180 const std::string calibration_filename =
181 FLAGS_calibration_folder +
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800182 absl::StrFormat("/calibration_pi-%d-%d_cam-%s_%s.json",
183 team_number.value(), pi_number_.value(), camera_id_,
184 time_ss.str());
Austin Schuh25837f22021-06-27 15:49:14 -0700185
186 LOG(INFO) << calibration_filename << " -> "
187 << aos::FlatbufferToJson(camera_calibration,
188 {.multi_line = true});
189
190 aos::util::WriteStringToFileOrDie(
191 calibration_filename,
192 aos::FlatbufferToJson(camera_calibration, {.multi_line = true}));
193 } else {
194 LOG(INFO) << "Skipping calibration due to not enough images.";
195 }
196 }
197
198 private:
Yash Chainani5c005da2022-01-22 16:51:11 -0800199 static constexpr double kDeltaRThreshold = M_PI / 6.0;
200 static constexpr double kDeltaTThreshold = 0.3;
201
Austin Schuh25837f22021-06-27 15:49:14 -0700202 aos::ShmEventLoop *event_loop_;
203 std::string pi_;
204 const std::optional<uint16_t> pi_number_;
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800205 const std::string camera_id_;
Austin Schuh25837f22021-06-27 15:49:14 -0700206
207 std::vector<std::vector<int>> all_charuco_ids_;
208 std::vector<std::vector<cv::Point2f>> all_charuco_corners_;
209
Yash Chainani460c9fb2022-02-12 18:14:50 -0800210 Eigen::Affine3d H_camera_board_;
211 Eigen::Affine3d prev_H_camera_board_;
Yash Chainani5c005da2022-01-22 16:51:11 -0800212
Austin Schuh25837f22021-06-27 15:49:14 -0700213 CharucoExtractor charuco_extractor_;
214};
215
216namespace {
217
218void Main() {
219 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
220 aos::configuration::ReadConfig(FLAGS_config);
221
222 aos::ShmEventLoop event_loop(&config.message());
223
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800224 std::string hostname = FLAGS_pi;
225 if (hostname == "") {
226 hostname = aos::network::GetHostname();
227 LOG(INFO) << "Using pi name from hostname as " << hostname;
228 }
229 Calibration extractor(&event_loop, hostname, FLAGS_camera_id);
Austin Schuhc1f118e2020-04-11 15:50:08 -0700230
231 event_loop.Run();
232
Austin Schuh25837f22021-06-27 15:49:14 -0700233 extractor.MaybeCalibrate();
Austin Schuhc1f118e2020-04-11 15:50:08 -0700234}
235
236} // namespace
237} // namespace vision
238} // namespace frc971
239
Austin Schuhc1f118e2020-04-11 15:50:08 -0700240int main(int argc, char **argv) {
241 aos::InitGoogle(&argc, &argv);
Austin Schuh25837f22021-06-27 15:49:14 -0700242 frc971::vision::Main();
Austin Schuhc1f118e2020-04-11 15:50:08 -0700243}