Brian Silverman | 36c7f34 | 2021-06-11 15:21:41 -0700 | [diff] [blame] | 1 | // These need to come before opencv, or they don't compile. Presumably opencv |
| 2 | // #defines something annoying. |
| 3 | // clang-format off |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 4 | #include "Eigen/Dense" |
| 5 | #include "Eigen/Geometry" |
Brian Silverman | 36c7f34 | 2021-06-11 15:21:41 -0700 | [diff] [blame] | 6 | // clang-format on |
| 7 | |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 8 | #include <opencv2/aruco/charuco.hpp> |
| 9 | #include <opencv2/calib3d.hpp> |
| 10 | #include <opencv2/core/eigen.hpp> |
| 11 | #include <opencv2/features2d.hpp> |
| 12 | #include <opencv2/highgui/highgui.hpp> |
| 13 | #include <opencv2/imgproc.hpp> |
| 14 | |
| 15 | #include "absl/strings/str_format.h" |
| 16 | #include "aos/events/shm_event_loop.h" |
| 17 | #include "aos/init.h" |
| 18 | #include "aos/network/team_number.h" |
| 19 | #include "aos/time/time.h" |
| 20 | #include "aos/util/file.h" |
| 21 | #include "frc971/control_loops/drivetrain/improved_down_estimator.h" |
| 22 | #include "y2020/vision/sift/sift_generated.h" |
| 23 | #include "y2020/vision/sift/sift_training_generated.h" |
| 24 | #include "y2020/vision/tools/python_code/sift_training_data.h" |
| 25 | #include "y2020/vision/vision_generated.h" |
| 26 | |
| 27 | DEFINE_string(config, "config.json", "Path to the config file to use."); |
| 28 | DEFINE_string(pi, "pi-7971-1", "Pi name to calibrate."); |
| 29 | DEFINE_string(calibration_folder, "y2020/vision/tools/python_code/calib_files", |
| 30 | "Folder to place calibration files."); |
| 31 | DEFINE_bool(large_board, true, "If true, use the large calibration board."); |
| 32 | DEFINE_bool(display_undistorted, false, |
| 33 | "If true, display the undistorted image."); |
| 34 | DEFINE_string(board_template_path, "", |
| 35 | "If specified, write an image to the specified path for the " |
| 36 | "charuco board pattern."); |
| 37 | DEFINE_uint32(min_targets, 10, |
| 38 | "The mininum number of targets required to match."); |
| 39 | |
| 40 | namespace frc971 { |
| 41 | namespace vision { |
| 42 | |
| 43 | class CameraCalibration { |
| 44 | public: |
Brian Silverman | 36c7f34 | 2021-06-11 15:21:41 -0700 | [diff] [blame] | 45 | CameraCalibration(const absl::Span<const uint8_t> training_data_bfbs) { |
| 46 | const aos::FlatbufferSpan<sift::TrainingData> training_data( |
| 47 | training_data_bfbs); |
| 48 | CHECK(training_data.Verify()); |
| 49 | camera_calibration_ = FindCameraCalibration(&training_data.message()); |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 50 | } |
| 51 | |
| 52 | cv::Mat CameraIntrinsics() const { |
| 53 | const cv::Mat result(3, 3, CV_32F, |
| 54 | const_cast<void *>(static_cast<const void *>( |
| 55 | camera_calibration_->intrinsics()->data()))); |
| 56 | CHECK_EQ(result.total(), camera_calibration_->intrinsics()->size()); |
| 57 | return result; |
| 58 | } |
| 59 | |
| 60 | cv::Mat CameraDistCoeffs() const { |
| 61 | const cv::Mat result(5, 1, CV_32F, |
| 62 | const_cast<void *>(static_cast<const void *>( |
| 63 | camera_calibration_->dist_coeffs()->data()))); |
| 64 | CHECK_EQ(result.total(), camera_calibration_->dist_coeffs()->size()); |
| 65 | return result; |
| 66 | } |
| 67 | |
| 68 | private: |
| 69 | const sift::CameraCalibration *FindCameraCalibration( |
| 70 | const sift::TrainingData *const training_data) const { |
| 71 | std::optional<uint16_t> pi_number = aos::network::ParsePiNumber(FLAGS_pi); |
| 72 | std::optional<uint16_t> team_number = |
| 73 | aos::network::team_number_internal::ParsePiTeamNumber(FLAGS_pi); |
| 74 | CHECK(pi_number); |
| 75 | CHECK(team_number); |
| 76 | const std::string node_name = absl::StrFormat("pi%d", pi_number.value()); |
| 77 | LOG(INFO) << "Looking for node name " << node_name << " team number " |
| 78 | << team_number.value(); |
| 79 | for (const sift::CameraCalibration *candidate : |
| 80 | *training_data->camera_calibrations()) { |
| 81 | if (candidate->node_name()->string_view() != node_name) { |
| 82 | continue; |
| 83 | } |
| 84 | if (candidate->team_number() != team_number.value()) { |
| 85 | continue; |
| 86 | } |
| 87 | return candidate; |
| 88 | } |
| 89 | LOG(FATAL) << ": Failed to find camera calibration for " << node_name |
| 90 | << " on " << team_number.value(); |
| 91 | } |
| 92 | |
| 93 | const sift::CameraCalibration *camera_calibration_; |
| 94 | }; |
| 95 | |
| 96 | namespace { |
| 97 | |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 98 | void ViewerMain() { |
| 99 | aos::FlatbufferDetachedBuffer<aos::Configuration> config = |
| 100 | aos::configuration::ReadConfig(FLAGS_config); |
| 101 | |
| 102 | aos::ShmEventLoop event_loop(&config.message()); |
| 103 | |
| 104 | const CameraCalibration calibration(SiftTrainingData()); |
| 105 | |
| 106 | cv::Ptr<cv::aruco::Dictionary> dictionary = |
| 107 | cv::aruco::getPredefinedDictionary(FLAGS_large_board |
| 108 | ? cv::aruco::DICT_5X5_100 |
| 109 | : cv::aruco::DICT_6X6_250); |
| 110 | cv::Ptr<cv::aruco::CharucoBoard> board = |
| 111 | FLAGS_large_board |
| 112 | ? cv::aruco::CharucoBoard::create(12, 9, 0.06, 0.045, dictionary) |
| 113 | : cv::aruco::CharucoBoard::create(7, 5, 0.04, 0.025, dictionary); |
| 114 | |
| 115 | if (!FLAGS_board_template_path.empty()) { |
| 116 | cv::Mat board_image; |
| 117 | board->draw(cv::Size(600, 500), board_image, 10, 1); |
| 118 | cv::imwrite(FLAGS_board_template_path, board_image); |
| 119 | } |
| 120 | |
| 121 | std::vector<std::vector<int>> all_charuco_ids; |
| 122 | std::vector<std::vector<cv::Point2f>> all_charuco_corners; |
| 123 | |
| 124 | const cv::Mat camera_matrix = calibration.CameraIntrinsics(); |
| 125 | Eigen::Matrix3d eigen_camera_matrix; |
| 126 | cv::cv2eigen(camera_matrix, eigen_camera_matrix); |
| 127 | |
| 128 | const cv::Mat dist_coeffs = calibration.CameraDistCoeffs(); |
| 129 | LOG(INFO) << "Camera matrix " << camera_matrix; |
| 130 | LOG(INFO) << "Distortion Coefficients " << dist_coeffs; |
| 131 | |
| 132 | std::optional<uint16_t> pi_number = aos::network::ParsePiNumber(FLAGS_pi); |
| 133 | CHECK(pi_number) << ": Invalid pi number " << FLAGS_pi |
| 134 | << ", failed to parse pi number"; |
| 135 | |
| 136 | const std::string channel = |
| 137 | absl::StrCat("/pi", std::to_string(pi_number.value()), "/camera"); |
| 138 | LOG(INFO) << "Connecting to channel " << channel; |
| 139 | |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 140 | event_loop.MakeWatcher(channel, [&event_loop, &board, &all_charuco_ids, |
| 141 | &all_charuco_corners, camera_matrix, |
| 142 | dist_coeffs, eigen_camera_matrix]( |
| 143 | const CameraImage &image) { |
| 144 | const aos::monotonic_clock::duration age = |
| 145 | event_loop.monotonic_now() - event_loop.context().monotonic_event_time; |
| 146 | const double age_double = |
| 147 | std::chrono::duration_cast<std::chrono::duration<double>>(age).count(); |
| 148 | if (age > std::chrono::milliseconds(100)) { |
| 149 | LOG(INFO) << "Age: " << age_double << ", getting behind, skipping"; |
| 150 | return; |
| 151 | } |
| 152 | // Create color image: |
| 153 | cv::Mat image_color_mat(cv::Size(image.cols(), image.rows()), CV_8UC2, |
| 154 | (void *)image.data()->data()); |
| 155 | const cv::Size image_size(image.cols(), image.rows()); |
| 156 | cv::Mat rgb_image(image_size, CV_8UC3); |
| 157 | cv::cvtColor(image_color_mat, rgb_image, CV_YUV2BGR_YUYV); |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 158 | |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 159 | std::vector<int> marker_ids; |
| 160 | std::vector<std::vector<cv::Point2f>> marker_corners; |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 161 | |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 162 | cv::aruco::detectMarkers(rgb_image, board->dictionary, marker_corners, |
| 163 | marker_ids); |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 164 | |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 165 | std::vector<cv::Point2f> charuco_corners; |
| 166 | std::vector<int> charuco_ids; |
| 167 | // If at least one marker detected |
| 168 | if (marker_ids.size() >= FLAGS_min_targets) { |
| 169 | // Run everything twice, once with the calibration, and once without. |
| 170 | // This lets us both calibrate, and also print out the pose real time |
| 171 | // with the previous calibration. |
| 172 | cv::aruco::interpolateCornersCharuco(marker_corners, marker_ids, |
| 173 | rgb_image, board, charuco_corners, |
| 174 | charuco_ids); |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 175 | |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 176 | std::vector<cv::Point2f> charuco_corners_with_calibration; |
| 177 | std::vector<int> charuco_ids_with_calibration; |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 178 | |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 179 | cv::aruco::interpolateCornersCharuco( |
| 180 | marker_corners, marker_ids, rgb_image, board, |
| 181 | charuco_corners_with_calibration, charuco_ids_with_calibration, |
| 182 | camera_matrix, dist_coeffs); |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 183 | |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 184 | cv::aruco::drawDetectedMarkers(rgb_image, marker_corners, marker_ids); |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 185 | |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 186 | if (charuco_ids.size() >= FLAGS_min_targets) { |
| 187 | cv::aruco::drawDetectedCornersCharuco( |
| 188 | rgb_image, charuco_corners, charuco_ids, cv::Scalar(255, 0, 0)); |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 189 | |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 190 | cv::Vec3d rvec, tvec; |
| 191 | bool valid = cv::aruco::estimatePoseCharucoBoard( |
| 192 | charuco_corners_with_calibration, charuco_ids_with_calibration, |
| 193 | board, camera_matrix, dist_coeffs, rvec, tvec); |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 194 | |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 195 | // if charuco pose is valid |
| 196 | if (valid) { |
| 197 | LOG(INFO) << std::fixed << std::setprecision(6) |
| 198 | << "Age: " << age_double << ", Pose is R:" << rvec |
| 199 | << " T:" << tvec; |
| 200 | cv::aruco::drawAxis(rgb_image, camera_matrix, dist_coeffs, rvec, tvec, |
| 201 | 0.1); |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 202 | } else { |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 203 | LOG(INFO) << "Age: " << age_double << ", invalid pose"; |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 204 | } |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 205 | } else { |
| 206 | LOG(INFO) << "Age: " << age_double << ", no charuco IDs."; |
| 207 | } |
| 208 | } else { |
| 209 | LOG(INFO) << "Age: " << age_double << ", no marker IDs"; |
| 210 | } |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 211 | |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 212 | cv::imshow("Display", rgb_image); |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 213 | |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 214 | if (FLAGS_display_undistorted) { |
| 215 | cv::Mat undistorted_rgb_image(image_size, CV_8UC3); |
| 216 | cv::undistort(rgb_image, undistorted_rgb_image, camera_matrix, |
| 217 | dist_coeffs); |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 218 | |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 219 | cv::imshow("Display undist", undistorted_rgb_image); |
| 220 | } |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 221 | |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 222 | int keystroke = cv::waitKey(1); |
| 223 | if ((keystroke & 0xFF) == static_cast<int>('c')) { |
| 224 | if (charuco_ids.size() >= FLAGS_min_targets) { |
| 225 | all_charuco_ids.emplace_back(std::move(charuco_ids)); |
| 226 | all_charuco_corners.emplace_back(std::move(charuco_corners)); |
| 227 | LOG(INFO) << "Image " << all_charuco_corners.size(); |
| 228 | } |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 229 | |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 230 | if (all_charuco_ids.size() >= 50) { |
| 231 | LOG(INFO) << "Got enough images to calibrate"; |
| 232 | event_loop.Exit(); |
| 233 | } |
| 234 | } else if ((keystroke & 0xFF) == static_cast<int>('q')) { |
| 235 | event_loop.Exit(); |
| 236 | } |
| 237 | }); |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 238 | |
| 239 | event_loop.Run(); |
| 240 | |
| 241 | if (all_charuco_ids.size() >= 50) { |
| 242 | cv::Mat cameraMatrix, distCoeffs; |
| 243 | std::vector<cv::Mat> rvecs, tvecs; |
| 244 | cv::Mat stdDeviationsIntrinsics, stdDeviationsExtrinsics, perViewErrors; |
| 245 | |
| 246 | // Set calibration flags (same than in calibrateCamera() function) |
| 247 | int calibration_flags = 0; |
| 248 | cv::Size img_size(640, 480); |
| 249 | const double reprojection_error = cv::aruco::calibrateCameraCharuco( |
| 250 | all_charuco_corners, all_charuco_ids, board, img_size, cameraMatrix, |
| 251 | distCoeffs, rvecs, tvecs, stdDeviationsIntrinsics, |
| 252 | stdDeviationsExtrinsics, perViewErrors, calibration_flags); |
| 253 | CHECK_LE(reprojection_error, 1.0) << ": Reproduction error is bad."; |
| 254 | LOG(INFO) << "Reprojection Error is " << reprojection_error; |
| 255 | |
| 256 | flatbuffers::FlatBufferBuilder fbb; |
| 257 | flatbuffers::Offset<flatbuffers::String> name_offset = |
| 258 | fbb.CreateString(absl::StrFormat("pi%d", pi_number.value())); |
| 259 | flatbuffers::Offset<flatbuffers::Vector<float>> intrinsics_offset = |
| 260 | fbb.CreateVector<float>(9u, [&cameraMatrix](size_t i) { |
| 261 | return static_cast<float>( |
| 262 | reinterpret_cast<double *>(cameraMatrix.data)[i]); |
| 263 | }); |
| 264 | |
| 265 | flatbuffers::Offset<flatbuffers::Vector<float>> |
| 266 | distortion_coefficients_offset = |
| 267 | fbb.CreateVector<float>(5u, [&distCoeffs](size_t i) { |
| 268 | return static_cast<float>( |
| 269 | reinterpret_cast<double *>(distCoeffs.data)[i]); |
| 270 | }); |
| 271 | |
| 272 | sift::CameraCalibration::Builder camera_calibration_builder(fbb); |
| 273 | std::optional<uint16_t> team_number = |
| 274 | aos::network::team_number_internal::ParsePiTeamNumber(FLAGS_pi); |
| 275 | CHECK(team_number) << ": Invalid pi hostname " << FLAGS_pi |
| 276 | << ", failed to parse team number"; |
| 277 | |
| 278 | const aos::realtime_clock::time_point realtime_now = |
| 279 | aos::realtime_clock::now(); |
| 280 | camera_calibration_builder.add_node_name(name_offset); |
| 281 | camera_calibration_builder.add_team_number(team_number.value()); |
| 282 | camera_calibration_builder.add_calibration_timestamp( |
| 283 | realtime_now.time_since_epoch().count()); |
| 284 | camera_calibration_builder.add_intrinsics(intrinsics_offset); |
| 285 | camera_calibration_builder.add_dist_coeffs(distortion_coefficients_offset); |
| 286 | camera_calibration_builder.add_dist_coeffs(distortion_coefficients_offset); |
| 287 | fbb.Finish(camera_calibration_builder.Finish()); |
| 288 | |
| 289 | aos::FlatbufferDetachedBuffer<sift::CameraCalibration> camera_calibration( |
| 290 | fbb.Release()); |
| 291 | std::stringstream time_ss; |
| 292 | time_ss << realtime_now; |
| 293 | |
| 294 | const std::string calibration_filename = |
| 295 | FLAGS_calibration_folder + |
| 296 | absl::StrFormat("/calibration_pi-%d-%d_%s.json", team_number.value(), |
| 297 | pi_number.value(), time_ss.str()); |
| 298 | |
| 299 | LOG(INFO) << calibration_filename << " -> " |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 300 | << aos::FlatbufferToJson(camera_calibration, |
| 301 | {.multi_line = true}); |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 302 | |
| 303 | aos::util::WriteStringToFileOrDie( |
Ravago Jones | cf453ab | 2020-05-06 21:14:53 -0700 | [diff] [blame] | 304 | calibration_filename, |
| 305 | aos::FlatbufferToJson(camera_calibration, {.multi_line = true})); |
Austin Schuh | c1f118e | 2020-04-11 15:50:08 -0700 | [diff] [blame] | 306 | } else { |
| 307 | LOG(INFO) << "Skipping calibration due to not enough images."; |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | } // namespace |
| 312 | } // namespace vision |
| 313 | } // namespace frc971 |
| 314 | |
| 315 | // Quick and lightweight grayscale viewer for images |
| 316 | int main(int argc, char **argv) { |
| 317 | aos::InitGoogle(&argc, &argv); |
| 318 | frc971::vision::ViewerMain(); |
| 319 | } |