blob: d5ed54fc0b6fd475a39ccce406250566d55b29ad [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_(
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -080038 event_loop, pi, TargetType::kCharuco, "/camera",
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);
milind-u0cb53112023-02-03 20:32:55 -080056 },
57 std::chrono::milliseconds(5)) {
Austin Schuh25837f22021-06-27 15:49:14 -070058 CHECK(pi_number_) << ": Invalid pi number " << pi
59 << ", failed to parse pi number";
Jim Ostrowskifec0c332022-02-06 23:28:26 -080060 std::regex re{"^[0-9][0-9]-[0-9][0-9]"};
61 CHECK(std::regex_match(camera_id_, re))
62 << ": Invalid camera_id '" << camera_id_
63 << "', should be of form YY-NN";
Austin Schuhc1f118e2020-04-11 15:50:08 -070064 }
65
Austin Schuhea7b0142021-10-08 22:04:53 -070066 void HandleCharuco(cv::Mat rgb_image,
67 const aos::monotonic_clock::time_point /*eof*/,
Jim Ostrowskib3cab972022-12-03 15:47:00 -080068 std::vector<cv::Vec4i> charuco_ids,
69 std::vector<std::vector<cv::Point2f>> charuco_corners,
70 bool valid, std::vector<Eigen::Vector3d> rvecs_eigen,
71 std::vector<Eigen::Vector3d> tvecs_eigen) {
Yash Chainani5c005da2022-01-22 16:51:11 -080072 // Reduce resolution displayed on remote viewer to prevent lag
73 cv::resize(rgb_image, rgb_image,
74 cv::Size(rgb_image.cols / 2, rgb_image.rows / 2));
Ravago Jonescf453ab2020-05-06 21:14:53 -070075 cv::imshow("Display", rgb_image);
Austin Schuhc1f118e2020-04-11 15:50:08 -070076
Ravago Jonescf453ab2020-05-06 21:14:53 -070077 if (FLAGS_display_undistorted) {
Austin Schuh25837f22021-06-27 15:49:14 -070078 const cv::Size image_size(rgb_image.cols, rgb_image.rows);
Ravago Jonescf453ab2020-05-06 21:14:53 -070079 cv::Mat undistorted_rgb_image(image_size, CV_8UC3);
Austin Schuh25837f22021-06-27 15:49:14 -070080 cv::undistort(rgb_image, undistorted_rgb_image,
81 charuco_extractor_.camera_matrix(),
82 charuco_extractor_.dist_coeffs());
Austin Schuhc1f118e2020-04-11 15:50:08 -070083
Ravago Jonescf453ab2020-05-06 21:14:53 -070084 cv::imshow("Display undist", undistorted_rgb_image);
85 }
Austin Schuhc1f118e2020-04-11 15:50:08 -070086
Jim Ostrowski634b2652022-03-04 02:10:53 -080087 int keystroke = cv::waitKey(1);
88
89 // If we haven't got a valid pose estimate, don't use these points
90 if (!valid) {
91 return;
92 }
Jim Ostrowskib3cab972022-12-03 15:47:00 -080093 CHECK(tvecs_eigen.size() == 1)
94 << "Charuco board should only return one translational pose";
95 CHECK(rvecs_eigen.size() == 1)
96 << "Charuco board should only return one rotational pose";
Yash Chainani5c005da2022-01-22 16:51:11 -080097 // Calibration calculates rotation and translation delta from last image
Yash Chainani24fc2bd2022-02-14 12:43:29 -080098 // stored to automatically capture next image
Yash Chainani5c005da2022-01-22 16:51:11 -080099
Yash Chainani460c9fb2022-02-12 18:14:50 -0800100 Eigen::Affine3d H_board_camera =
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800101 Eigen::Translation3d(tvecs_eigen[0]) *
102 Eigen::AngleAxisd(rvecs_eigen[0].norm(),
103 rvecs_eigen[0] / rvecs_eigen[0].norm());
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800104 Eigen::Affine3d H_camera_board_ = H_board_camera.inverse();
Yash Chainani460c9fb2022-02-12 18:14:50 -0800105 Eigen::Affine3d H_delta = H_board_camera * prev_H_camera_board_;
Yash Chainani5c005da2022-01-22 16:51:11 -0800106
Yash Chainani460c9fb2022-02-12 18:14:50 -0800107 Eigen::AngleAxisd delta_r = Eigen::AngleAxisd(H_delta.rotation());
Yash Chainani5c005da2022-01-22 16:51:11 -0800108
Yash Chainani460c9fb2022-02-12 18:14:50 -0800109 Eigen::Vector3d delta_t = H_delta.translation();
Yash Chainani5c005da2022-01-22 16:51:11 -0800110
111 double r_norm = std::abs(delta_r.angle());
112 double t_norm = delta_t.norm();
113
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800114 bool store_image = false;
Jim Ostrowski634b2652022-03-04 02:10:53 -0800115 double percent_motion =
116 std::max<double>(r_norm / kDeltaRThreshold, t_norm / kDeltaTThreshold);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800117 LOG(INFO) << "Captured: " << all_charuco_ids_.size() << " points; Moved "
118 << percent_motion << "% of what's needed";
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800119 // Verify that camera has moved enough from last stored image
Yash Chainani5c005da2022-01-22 16:51:11 -0800120 if (r_norm > kDeltaRThreshold || t_norm > kDeltaTThreshold) {
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800121 // frame_ refers to deltas between current and last captured image
122 Eigen::Affine3d frame_H_delta =
123 H_board_camera * prev_image_H_camera_board_;
124
125 Eigen::AngleAxisd frame_delta_r =
126 Eigen::AngleAxisd(frame_H_delta.rotation());
127
128 Eigen::Vector3d frame_delta_t = frame_H_delta.translation();
129
130 double frame_r_norm = std::abs(frame_delta_r.angle());
131 double frame_t_norm = frame_delta_t.norm();
132
133 // Make sure camera has stopped moving before storing image
134 store_image =
135 frame_r_norm < kFrameDeltaRLimit && frame_t_norm < kFrameDeltaTLimit;
Jim Ostrowski634b2652022-03-04 02:10:53 -0800136 double percent_stop = std::max<double>(frame_r_norm / kFrameDeltaRLimit,
137 frame_t_norm / kFrameDeltaTLimit);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800138 LOG(INFO) << "Captured: " << all_charuco_ids_.size()
139 << "points; Moved enough (" << percent_motion
140 << "%); Need to stop (last motion was " << percent_stop
141 << "% of limit; needs to be < 1 to capture)";
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800142 }
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800143 prev_image_H_camera_board_ = H_camera_board_;
144
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800145 if (store_image) {
Austin Schuh25837f22021-06-27 15:49:14 -0700146 if (valid) {
Yash Chainani460c9fb2022-02-12 18:14:50 -0800147 prev_H_camera_board_ = H_camera_board_;
Yash Chainani5c005da2022-01-22 16:51:11 -0800148
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800149 // Unpack the Charuco ids from Vec4i
150 std::vector<int> charuco_ids_int;
151 for (cv::Vec4i charuco_id : charuco_ids) {
152 charuco_ids_int.emplace_back(charuco_id[0]);
153 }
154 all_charuco_ids_.emplace_back(std::move(charuco_ids_int));
155 all_charuco_corners_.emplace_back(std::move(charuco_corners[0]));
Yash Chainani5c005da2022-01-22 16:51:11 -0800156
157 if (r_norm > kDeltaRThreshold) {
158 LOG(INFO) << "Triggered by rotation delta = " << r_norm << " > "
159 << kDeltaRThreshold;
160 }
161 if (t_norm > kDeltaTThreshold) {
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800162 LOG(INFO) << "Triggered by translation delta = " << t_norm << " > "
Yash Chainani5c005da2022-01-22 16:51:11 -0800163 << kDeltaTThreshold;
164 }
Ravago Jonescf453ab2020-05-06 21:14:53 -0700165 }
Austin Schuhc1f118e2020-04-11 15:50:08 -0700166
Ravago Jonescf453ab2020-05-06 21:14:53 -0700167 } else if ((keystroke & 0xFF) == static_cast<int>('q')) {
Austin Schuh25837f22021-06-27 15:49:14 -0700168 event_loop_->Exit();
Ravago Jonescf453ab2020-05-06 21:14:53 -0700169 }
Austin Schuh25837f22021-06-27 15:49:14 -0700170 }
171
172 void MaybeCalibrate() {
Jim Ostrowski634b2652022-03-04 02:10:53 -0800173 // TODO: This number should depend on coarse vs. fine pattern
174 // Maybe just on total # of ids found, not just images
Austin Schuh25837f22021-06-27 15:49:14 -0700175 if (all_charuco_ids_.size() >= 50) {
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800176 LOG(INFO) << "Beginning calibration on " << all_charuco_ids_.size()
177 << " images";
Austin Schuh25837f22021-06-27 15:49:14 -0700178 cv::Mat cameraMatrix, distCoeffs;
179 std::vector<cv::Mat> rvecs, tvecs;
180 cv::Mat stdDeviationsIntrinsics, stdDeviationsExtrinsics, perViewErrors;
181
182 // Set calibration flags (same as in calibrateCamera() function)
183 int calibration_flags = 0;
184 cv::Size img_size(640, 480);
185 const double reprojection_error = cv::aruco::calibrateCameraCharuco(
186 all_charuco_corners_, all_charuco_ids_, charuco_extractor_.board(),
187 img_size, cameraMatrix, distCoeffs, rvecs, tvecs,
188 stdDeviationsIntrinsics, stdDeviationsExtrinsics, perViewErrors,
189 calibration_flags);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800190 CHECK_LE(reprojection_error, 1.0)
191 << ": Reproduction error is bad-- greater than 1 pixel.";
Austin Schuh25837f22021-06-27 15:49:14 -0700192 LOG(INFO) << "Reprojection Error is " << reprojection_error;
193
194 flatbuffers::FlatBufferBuilder fbb;
195 flatbuffers::Offset<flatbuffers::String> name_offset =
196 fbb.CreateString(absl::StrFormat("pi%d", pi_number_.value()));
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800197 flatbuffers::Offset<flatbuffers::String> camera_id_offset =
198 fbb.CreateString(camera_id_);
Austin Schuh25837f22021-06-27 15:49:14 -0700199 flatbuffers::Offset<flatbuffers::Vector<float>> intrinsics_offset =
200 fbb.CreateVector<float>(9u, [&cameraMatrix](size_t i) {
201 return static_cast<float>(
202 reinterpret_cast<double *>(cameraMatrix.data)[i]);
203 });
204
205 flatbuffers::Offset<flatbuffers::Vector<float>>
206 distortion_coefficients_offset =
207 fbb.CreateVector<float>(5u, [&distCoeffs](size_t i) {
208 return static_cast<float>(
209 reinterpret_cast<double *>(distCoeffs.data)[i]);
210 });
211
212 sift::CameraCalibration::Builder camera_calibration_builder(fbb);
213 std::optional<uint16_t> team_number =
214 aos::network::team_number_internal::ParsePiTeamNumber(pi_);
215 CHECK(team_number) << ": Invalid pi hostname " << pi_
216 << ", failed to parse team number";
217
218 const aos::realtime_clock::time_point realtime_now =
219 aos::realtime_clock::now();
220 camera_calibration_builder.add_node_name(name_offset);
221 camera_calibration_builder.add_team_number(team_number.value());
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800222 camera_calibration_builder.add_camera_id(camera_id_offset);
Austin Schuh25837f22021-06-27 15:49:14 -0700223 camera_calibration_builder.add_calibration_timestamp(
224 realtime_now.time_since_epoch().count());
225 camera_calibration_builder.add_intrinsics(intrinsics_offset);
226 camera_calibration_builder.add_dist_coeffs(
227 distortion_coefficients_offset);
228 fbb.Finish(camera_calibration_builder.Finish());
229
230 aos::FlatbufferDetachedBuffer<sift::CameraCalibration> camera_calibration(
231 fbb.Release());
232 std::stringstream time_ss;
233 time_ss << realtime_now;
234
235 const std::string calibration_filename =
236 FLAGS_calibration_folder +
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800237 absl::StrFormat("/calibration_pi-%d-%d_cam-%s_%s.json",
238 team_number.value(), pi_number_.value(), camera_id_,
239 time_ss.str());
Austin Schuh25837f22021-06-27 15:49:14 -0700240
241 LOG(INFO) << calibration_filename << " -> "
242 << aos::FlatbufferToJson(camera_calibration,
243 {.multi_line = true});
244
245 aos::util::WriteStringToFileOrDie(
246 calibration_filename,
247 aos::FlatbufferToJson(camera_calibration, {.multi_line = true}));
248 } else {
249 LOG(INFO) << "Skipping calibration due to not enough images.";
250 }
251 }
252
253 private:
Yash Chainani5c005da2022-01-22 16:51:11 -0800254 static constexpr double kDeltaRThreshold = M_PI / 6.0;
255 static constexpr double kDeltaTThreshold = 0.3;
256
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800257 static constexpr double kFrameDeltaRLimit = M_PI / 60;
258 static constexpr double kFrameDeltaTLimit = 0.01;
259
Austin Schuh25837f22021-06-27 15:49:14 -0700260 aos::ShmEventLoop *event_loop_;
261 std::string pi_;
262 const std::optional<uint16_t> pi_number_;
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800263 const std::string camera_id_;
Austin Schuh25837f22021-06-27 15:49:14 -0700264
265 std::vector<std::vector<int>> all_charuco_ids_;
266 std::vector<std::vector<cv::Point2f>> all_charuco_corners_;
267
Yash Chainani460c9fb2022-02-12 18:14:50 -0800268 Eigen::Affine3d H_camera_board_;
269 Eigen::Affine3d prev_H_camera_board_;
Yash Chainani24fc2bd2022-02-14 12:43:29 -0800270 Eigen::Affine3d prev_image_H_camera_board_;
Yash Chainani5c005da2022-01-22 16:51:11 -0800271
Austin Schuh25837f22021-06-27 15:49:14 -0700272 CharucoExtractor charuco_extractor_;
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800273 ImageCallback image_callback_;
Austin Schuh25837f22021-06-27 15:49:14 -0700274};
275
276namespace {
277
278void Main() {
279 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
280 aos::configuration::ReadConfig(FLAGS_config);
281
282 aos::ShmEventLoop event_loop(&config.message());
283
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800284 std::string hostname = FLAGS_pi;
285 if (hostname == "") {
286 hostname = aos::network::GetHostname();
287 LOG(INFO) << "Using pi name from hostname as " << hostname;
288 }
289 Calibration extractor(&event_loop, hostname, FLAGS_camera_id);
Austin Schuhc1f118e2020-04-11 15:50:08 -0700290
291 event_loop.Run();
292
Austin Schuh25837f22021-06-27 15:49:14 -0700293 extractor.MaybeCalibrate();
Austin Schuhc1f118e2020-04-11 15:50:08 -0700294}
295
296} // namespace
297} // namespace vision
298} // namespace frc971
299
Austin Schuhc1f118e2020-04-11 15:50:08 -0700300int main(int argc, char **argv) {
301 aos::InitGoogle(&argc, &argv);
Austin Schuh25837f22021-06-27 15:49:14 -0700302 frc971::vision::Main();
Austin Schuhc1f118e2020-04-11 15:50:08 -0700303}