blob: c6bacdb2f10ece6f47d0b9d8f19f50b7ae7af1e6 [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"
Austin Schuhdcb6b362022-02-25 18:06:21 -080015#include "frc971/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.");
Austin Schuhc5fa6d92022-02-25 14:36:28 -080019DEFINE_string(config, "aos_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 prev_H_camera_board_(Eigen::Affine3d()),
Yash Chainani24fc2bd2022-02-14 12:43:29 -080036 prev_image_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,
Jim Ostrowskib3cab972022-12-03 15:47:00 -080041 std::vector<cv::Vec4i> charuco_ids,
42 std::vector<std::vector<cv::Point2f>> charuco_corners,
43 bool valid, std::vector<Eigen::Vector3d> rvecs_eigen,
44 std::vector<Eigen::Vector3d> tvecs_eigen) {
Jim Ostrowskifec0c332022-02-06 23:28:26 -080045 HandleCharuco(rgb_image, eof, charuco_ids, charuco_corners, valid,
Jim Ostrowskib3cab972022-12-03 15:47:00 -080046 rvecs_eigen, tvecs_eigen);
47 }),
48 image_callback_(
49 event_loop,
50 absl::StrCat(
51 "/pi", std::to_string(aos::network::ParsePiNumber(pi).value()),
52 "/camera"),
53 [this](cv::Mat rgb_image,
54 const aos::monotonic_clock::time_point eof) {
55 charuco_extractor_.HandleImage(rgb_image, eof);
Austin Schuh25837f22021-06-27 15:49:14 -070056 }) {
57 CHECK(pi_number_) << ": Invalid pi number " << pi
58 << ", failed to parse pi number";
Jim Ostrowskifec0c332022-02-06 23:28:26 -080059 std::regex re{"^[0-9][0-9]-[0-9][0-9]"};
60 CHECK(std::regex_match(camera_id_, re))
61 << ": Invalid camera_id '" << camera_id_
62 << "', should be of form YY-NN";
Jim Ostrowskib3cab972022-12-03 15:47:00 -080063 CHECK_EQ(FLAGS_target_type, "charuco")
64 << "Intrinsic calibration only works with Charuco board";
Austin Schuhc1f118e2020-04-11 15:50:08 -070065 }
66
Austin Schuhea7b0142021-10-08 22:04:53 -070067 void HandleCharuco(cv::Mat rgb_image,
68 const aos::monotonic_clock::time_point /*eof*/,
Jim Ostrowskib3cab972022-12-03 15:47:00 -080069 std::vector<cv::Vec4i> charuco_ids,
70 std::vector<std::vector<cv::Point2f>> charuco_corners,
71 bool valid, std::vector<Eigen::Vector3d> rvecs_eigen,
72 std::vector<Eigen::Vector3d> tvecs_eigen) {
Yash Chainani5c005da2022-01-22 16:51:11 -080073 // Reduce resolution displayed on remote viewer to prevent lag
74 cv::resize(rgb_image, rgb_image,
75 cv::Size(rgb_image.cols / 2, rgb_image.rows / 2));
Ravago Jonescf453ab2020-05-06 21:14:53 -070076 cv::imshow("Display", rgb_image);
Austin Schuhc1f118e2020-04-11 15:50:08 -070077
Ravago Jonescf453ab2020-05-06 21:14:53 -070078 if (FLAGS_display_undistorted) {
Austin Schuh25837f22021-06-27 15:49:14 -070079 const cv::Size image_size(rgb_image.cols, rgb_image.rows);
Ravago Jonescf453ab2020-05-06 21:14:53 -070080 cv::Mat undistorted_rgb_image(image_size, CV_8UC3);
Austin Schuh25837f22021-06-27 15:49:14 -070081 cv::undistort(rgb_image, undistorted_rgb_image,
82 charuco_extractor_.camera_matrix(),
83 charuco_extractor_.dist_coeffs());
Austin Schuhc1f118e2020-04-11 15:50:08 -070084
Ravago Jonescf453ab2020-05-06 21:14:53 -070085 cv::imshow("Display undist", undistorted_rgb_image);
86 }
Austin Schuhc1f118e2020-04-11 15:50:08 -070087
Jim Ostrowski634b2652022-03-04 02:10:53 -080088 int keystroke = cv::waitKey(1);
89
90 // If we haven't got a valid pose estimate, don't use these points
91 if (!valid) {
92 return;
93 }
Jim Ostrowskib3cab972022-12-03 15:47:00 -080094 CHECK(tvecs_eigen.size() == 1)
95 << "Charuco board should only return one translational pose";
96 CHECK(rvecs_eigen.size() == 1)
97 << "Charuco board should only return one rotational pose";
Yash Chainani5c005da2022-01-22 16:51:11 -080098 // Calibration calculates rotation and translation delta from last image
Yash Chainani24fc2bd2022-02-14 12:43:29 -080099 // stored to automatically capture next image
Yash Chainani5c005da2022-01-22 16:51:11 -0800100
Yash Chainani460c9fb2022-02-12 18:14:50 -0800101 Eigen::Affine3d H_board_camera =
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800102 Eigen::Translation3d(tvecs_eigen[0]) *
103 Eigen::AngleAxisd(rvecs_eigen[0].norm(),
104 rvecs_eigen[0] / rvecs_eigen[0].norm());
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800105 Eigen::Affine3d H_camera_board_ = H_board_camera.inverse();
Yash Chainani460c9fb2022-02-12 18:14:50 -0800106 Eigen::Affine3d H_delta = H_board_camera * prev_H_camera_board_;
Yash Chainani5c005da2022-01-22 16:51:11 -0800107
Yash Chainani460c9fb2022-02-12 18:14:50 -0800108 Eigen::AngleAxisd delta_r = Eigen::AngleAxisd(H_delta.rotation());
Yash Chainani5c005da2022-01-22 16:51:11 -0800109
Yash Chainani460c9fb2022-02-12 18:14:50 -0800110 Eigen::Vector3d delta_t = H_delta.translation();
Yash Chainani5c005da2022-01-22 16:51:11 -0800111
112 double r_norm = std::abs(delta_r.angle());
113 double t_norm = delta_t.norm();
114
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800115 bool store_image = false;
Jim Ostrowski634b2652022-03-04 02:10:53 -0800116 double percent_motion =
117 std::max<double>(r_norm / kDeltaRThreshold, t_norm / kDeltaTThreshold);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800118 LOG(INFO) << "Captured: " << all_charuco_ids_.size() << " points; Moved "
119 << percent_motion << "% of what's needed";
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800120 // Verify that camera has moved enough from last stored image
Yash Chainani5c005da2022-01-22 16:51:11 -0800121 if (r_norm > kDeltaRThreshold || t_norm > kDeltaTThreshold) {
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800122 // frame_ refers to deltas between current and last captured image
123 Eigen::Affine3d frame_H_delta =
124 H_board_camera * prev_image_H_camera_board_;
125
126 Eigen::AngleAxisd frame_delta_r =
127 Eigen::AngleAxisd(frame_H_delta.rotation());
128
129 Eigen::Vector3d frame_delta_t = frame_H_delta.translation();
130
131 double frame_r_norm = std::abs(frame_delta_r.angle());
132 double frame_t_norm = frame_delta_t.norm();
133
134 // Make sure camera has stopped moving before storing image
135 store_image =
136 frame_r_norm < kFrameDeltaRLimit && frame_t_norm < kFrameDeltaTLimit;
Jim Ostrowski634b2652022-03-04 02:10:53 -0800137 double percent_stop = std::max<double>(frame_r_norm / kFrameDeltaRLimit,
138 frame_t_norm / kFrameDeltaTLimit);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800139 LOG(INFO) << "Captured: " << all_charuco_ids_.size()
140 << "points; Moved enough (" << percent_motion
141 << "%); Need to stop (last motion was " << percent_stop
142 << "% of limit; needs to be < 1 to capture)";
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800143 }
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800144 prev_image_H_camera_board_ = H_camera_board_;
145
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800146 if (store_image) {
Austin Schuh25837f22021-06-27 15:49:14 -0700147 if (valid) {
Yash Chainani460c9fb2022-02-12 18:14:50 -0800148 prev_H_camera_board_ = H_camera_board_;
Yash Chainani5c005da2022-01-22 16:51:11 -0800149
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800150 // Unpack the Charuco ids from Vec4i
151 std::vector<int> charuco_ids_int;
152 for (cv::Vec4i charuco_id : charuco_ids) {
153 charuco_ids_int.emplace_back(charuco_id[0]);
154 }
155 all_charuco_ids_.emplace_back(std::move(charuco_ids_int));
156 all_charuco_corners_.emplace_back(std::move(charuco_corners[0]));
Yash Chainani5c005da2022-01-22 16:51:11 -0800157
158 if (r_norm > kDeltaRThreshold) {
159 LOG(INFO) << "Triggered by rotation delta = " << r_norm << " > "
160 << kDeltaRThreshold;
161 }
162 if (t_norm > kDeltaTThreshold) {
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800163 LOG(INFO) << "Triggered by translation delta = " << t_norm << " > "
Yash Chainani5c005da2022-01-22 16:51:11 -0800164 << kDeltaTThreshold;
165 }
Ravago Jonescf453ab2020-05-06 21:14:53 -0700166 }
Austin Schuhc1f118e2020-04-11 15:50:08 -0700167
Ravago Jonescf453ab2020-05-06 21:14:53 -0700168 } else if ((keystroke & 0xFF) == static_cast<int>('q')) {
Austin Schuh25837f22021-06-27 15:49:14 -0700169 event_loop_->Exit();
Ravago Jonescf453ab2020-05-06 21:14:53 -0700170 }
Austin Schuh25837f22021-06-27 15:49:14 -0700171 }
172
173 void MaybeCalibrate() {
Jim Ostrowski634b2652022-03-04 02:10:53 -0800174 // TODO: This number should depend on coarse vs. fine pattern
175 // Maybe just on total # of ids found, not just images
Austin Schuh25837f22021-06-27 15:49:14 -0700176 if (all_charuco_ids_.size() >= 50) {
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800177 LOG(INFO) << "Beginning calibration on " << all_charuco_ids_.size()
178 << " images";
Austin Schuh25837f22021-06-27 15:49:14 -0700179 cv::Mat cameraMatrix, distCoeffs;
180 std::vector<cv::Mat> rvecs, tvecs;
181 cv::Mat stdDeviationsIntrinsics, stdDeviationsExtrinsics, perViewErrors;
182
183 // Set calibration flags (same as in calibrateCamera() function)
184 int calibration_flags = 0;
185 cv::Size img_size(640, 480);
186 const double reprojection_error = cv::aruco::calibrateCameraCharuco(
187 all_charuco_corners_, all_charuco_ids_, charuco_extractor_.board(),
188 img_size, cameraMatrix, distCoeffs, rvecs, tvecs,
189 stdDeviationsIntrinsics, stdDeviationsExtrinsics, perViewErrors,
190 calibration_flags);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800191 CHECK_LE(reprojection_error, 1.0)
192 << ": Reproduction error is bad-- greater than 1 pixel.";
Austin Schuh25837f22021-06-27 15:49:14 -0700193 LOG(INFO) << "Reprojection Error is " << reprojection_error;
194
195 flatbuffers::FlatBufferBuilder fbb;
196 flatbuffers::Offset<flatbuffers::String> name_offset =
197 fbb.CreateString(absl::StrFormat("pi%d", pi_number_.value()));
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800198 flatbuffers::Offset<flatbuffers::String> camera_id_offset =
199 fbb.CreateString(camera_id_);
Austin Schuh25837f22021-06-27 15:49:14 -0700200 flatbuffers::Offset<flatbuffers::Vector<float>> intrinsics_offset =
201 fbb.CreateVector<float>(9u, [&cameraMatrix](size_t i) {
202 return static_cast<float>(
203 reinterpret_cast<double *>(cameraMatrix.data)[i]);
204 });
205
206 flatbuffers::Offset<flatbuffers::Vector<float>>
207 distortion_coefficients_offset =
208 fbb.CreateVector<float>(5u, [&distCoeffs](size_t i) {
209 return static_cast<float>(
210 reinterpret_cast<double *>(distCoeffs.data)[i]);
211 });
212
213 sift::CameraCalibration::Builder camera_calibration_builder(fbb);
214 std::optional<uint16_t> team_number =
215 aos::network::team_number_internal::ParsePiTeamNumber(pi_);
216 CHECK(team_number) << ": Invalid pi hostname " << pi_
217 << ", failed to parse team number";
218
219 const aos::realtime_clock::time_point realtime_now =
220 aos::realtime_clock::now();
221 camera_calibration_builder.add_node_name(name_offset);
222 camera_calibration_builder.add_team_number(team_number.value());
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800223 camera_calibration_builder.add_camera_id(camera_id_offset);
Austin Schuh25837f22021-06-27 15:49:14 -0700224 camera_calibration_builder.add_calibration_timestamp(
225 realtime_now.time_since_epoch().count());
226 camera_calibration_builder.add_intrinsics(intrinsics_offset);
227 camera_calibration_builder.add_dist_coeffs(
228 distortion_coefficients_offset);
229 fbb.Finish(camera_calibration_builder.Finish());
230
231 aos::FlatbufferDetachedBuffer<sift::CameraCalibration> camera_calibration(
232 fbb.Release());
233 std::stringstream time_ss;
234 time_ss << realtime_now;
235
236 const std::string calibration_filename =
237 FLAGS_calibration_folder +
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800238 absl::StrFormat("/calibration_pi-%d-%d_cam-%s_%s.json",
239 team_number.value(), pi_number_.value(), camera_id_,
240 time_ss.str());
Austin Schuh25837f22021-06-27 15:49:14 -0700241
242 LOG(INFO) << calibration_filename << " -> "
243 << aos::FlatbufferToJson(camera_calibration,
244 {.multi_line = true});
245
246 aos::util::WriteStringToFileOrDie(
247 calibration_filename,
248 aos::FlatbufferToJson(camera_calibration, {.multi_line = true}));
249 } else {
250 LOG(INFO) << "Skipping calibration due to not enough images.";
251 }
252 }
253
254 private:
Yash Chainani5c005da2022-01-22 16:51:11 -0800255 static constexpr double kDeltaRThreshold = M_PI / 6.0;
256 static constexpr double kDeltaTThreshold = 0.3;
257
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800258 static constexpr double kFrameDeltaRLimit = M_PI / 60;
259 static constexpr double kFrameDeltaTLimit = 0.01;
260
Austin Schuh25837f22021-06-27 15:49:14 -0700261 aos::ShmEventLoop *event_loop_;
262 std::string pi_;
263 const std::optional<uint16_t> pi_number_;
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800264 const std::string camera_id_;
Austin Schuh25837f22021-06-27 15:49:14 -0700265
266 std::vector<std::vector<int>> all_charuco_ids_;
267 std::vector<std::vector<cv::Point2f>> all_charuco_corners_;
268
Yash Chainani460c9fb2022-02-12 18:14:50 -0800269 Eigen::Affine3d H_camera_board_;
270 Eigen::Affine3d prev_H_camera_board_;
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800271 Eigen::Affine3d prev_image_H_camera_board_;
Yash Chainani5c005da2022-01-22 16:51:11 -0800272
Austin Schuh25837f22021-06-27 15:49:14 -0700273 CharucoExtractor charuco_extractor_;
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800274 ImageCallback image_callback_;
Austin Schuh25837f22021-06-27 15:49:14 -0700275};
276
277namespace {
278
279void Main() {
280 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
281 aos::configuration::ReadConfig(FLAGS_config);
282
283 aos::ShmEventLoop event_loop(&config.message());
284
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800285 std::string hostname = FLAGS_pi;
286 if (hostname == "") {
287 hostname = aos::network::GetHostname();
288 LOG(INFO) << "Using pi name from hostname as " << hostname;
289 }
290 Calibration extractor(&event_loop, hostname, FLAGS_camera_id);
Austin Schuhc1f118e2020-04-11 15:50:08 -0700291
292 event_loop.Run();
293
Austin Schuh25837f22021-06-27 15:49:14 -0700294 extractor.MaybeCalibrate();
Austin Schuhc1f118e2020-04-11 15:50:08 -0700295}
296
297} // namespace
298} // namespace vision
299} // namespace frc971
300
Austin Schuhc1f118e2020-04-11 15:50:08 -0700301int main(int argc, char **argv) {
302 aos::InitGoogle(&argc, &argv);
Austin Schuh25837f22021-06-27 15:49:14 -0700303 frc971::vision::Main();
Austin Schuhc1f118e2020-04-11 15:50:08 -0700304}