blob: 68002dba5f1b69d5244f3932038ce745a15174ce [file] [log] [blame]
Brian Silverman36c7f342021-06-11 15:21:41 -07001// These need to come before opencv, or they don't compile. Presumably opencv
2// #defines something annoying.
3// clang-format off
Austin Schuhc1f118e2020-04-11 15:50:08 -07004#include "Eigen/Dense"
5#include "Eigen/Geometry"
Brian Silverman36c7f342021-06-11 15:21:41 -07006// clang-format on
7
Austin Schuhc1f118e2020-04-11 15:50:08 -07008#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
27DEFINE_string(config, "config.json", "Path to the config file to use.");
28DEFINE_string(pi, "pi-7971-1", "Pi name to calibrate.");
29DEFINE_string(calibration_folder, "y2020/vision/tools/python_code/calib_files",
30 "Folder to place calibration files.");
31DEFINE_bool(large_board, true, "If true, use the large calibration board.");
Jim Ostrowski8c598af2021-09-11 17:18:18 -070032DEFINE_bool(coarse_pattern, true, "If true, use coarse arucos; else, use fine");
Austin Schuhc1f118e2020-04-11 15:50:08 -070033DEFINE_bool(display_undistorted, false,
34 "If true, display the undistorted image.");
35DEFINE_string(board_template_path, "",
36 "If specified, write an image to the specified path for the "
37 "charuco board pattern.");
38DEFINE_uint32(min_targets, 10,
39 "The mininum number of targets required to match.");
40
41namespace frc971 {
42namespace vision {
43
44class CameraCalibration {
45 public:
Brian Silverman36c7f342021-06-11 15:21:41 -070046 CameraCalibration(const absl::Span<const uint8_t> training_data_bfbs) {
47 const aos::FlatbufferSpan<sift::TrainingData> training_data(
48 training_data_bfbs);
49 CHECK(training_data.Verify());
50 camera_calibration_ = FindCameraCalibration(&training_data.message());
Austin Schuhc1f118e2020-04-11 15:50:08 -070051 }
52
53 cv::Mat CameraIntrinsics() const {
54 const cv::Mat result(3, 3, CV_32F,
55 const_cast<void *>(static_cast<const void *>(
56 camera_calibration_->intrinsics()->data())));
57 CHECK_EQ(result.total(), camera_calibration_->intrinsics()->size());
58 return result;
59 }
60
61 cv::Mat CameraDistCoeffs() const {
62 const cv::Mat result(5, 1, CV_32F,
63 const_cast<void *>(static_cast<const void *>(
64 camera_calibration_->dist_coeffs()->data())));
65 CHECK_EQ(result.total(), camera_calibration_->dist_coeffs()->size());
66 return result;
67 }
68
69 private:
70 const sift::CameraCalibration *FindCameraCalibration(
71 const sift::TrainingData *const training_data) const {
72 std::optional<uint16_t> pi_number = aos::network::ParsePiNumber(FLAGS_pi);
73 std::optional<uint16_t> team_number =
74 aos::network::team_number_internal::ParsePiTeamNumber(FLAGS_pi);
75 CHECK(pi_number);
76 CHECK(team_number);
77 const std::string node_name = absl::StrFormat("pi%d", pi_number.value());
78 LOG(INFO) << "Looking for node name " << node_name << " team number "
79 << team_number.value();
80 for (const sift::CameraCalibration *candidate :
81 *training_data->camera_calibrations()) {
82 if (candidate->node_name()->string_view() != node_name) {
83 continue;
84 }
85 if (candidate->team_number() != team_number.value()) {
86 continue;
87 }
88 return candidate;
89 }
90 LOG(FATAL) << ": Failed to find camera calibration for " << node_name
91 << " on " << team_number.value();
92 }
93
94 const sift::CameraCalibration *camera_calibration_;
95};
96
97namespace {
98
Austin Schuhc1f118e2020-04-11 15:50:08 -070099void ViewerMain() {
100 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
101 aos::configuration::ReadConfig(FLAGS_config);
102
103 aos::ShmEventLoop event_loop(&config.message());
104
105 const CameraCalibration calibration(SiftTrainingData());
106
107 cv::Ptr<cv::aruco::Dictionary> dictionary =
108 cv::aruco::getPredefinedDictionary(FLAGS_large_board
Jim Ostrowski8c598af2021-09-11 17:18:18 -0700109 ? cv::aruco::DICT_5X5_250
Austin Schuhc1f118e2020-04-11 15:50:08 -0700110 : cv::aruco::DICT_6X6_250);
Jim Ostrowski8c598af2021-09-11 17:18:18 -0700111
112 LOG(INFO) << "Using " << (FLAGS_large_board ? "large" : "small")
113 << " board with " << (FLAGS_coarse_pattern ? "coarse" : "fine")
114 << " pattern";
Austin Schuhc1f118e2020-04-11 15:50:08 -0700115 cv::Ptr<cv::aruco::CharucoBoard> board =
116 FLAGS_large_board
Jim Ostrowski8c598af2021-09-11 17:18:18 -0700117 ? (FLAGS_coarse_pattern ? cv::aruco::CharucoBoard::create(
118 12, 9, 0.06, 0.04666, dictionary)
119 : cv::aruco::CharucoBoard::create(
120 25, 18, 0.03, 0.0233, dictionary))
121 : (FLAGS_coarse_pattern ? cv::aruco::CharucoBoard::create(
122 7, 5, 0.04, 0.025, dictionary)
123 // TODO: Need to figure out what size is
124 // for small board, fine pattern
125 : cv::aruco::CharucoBoard::create(
126 7, 5, 0.03, 0.0233, dictionary));
Austin Schuhc1f118e2020-04-11 15:50:08 -0700127
128 if (!FLAGS_board_template_path.empty()) {
129 cv::Mat board_image;
130 board->draw(cv::Size(600, 500), board_image, 10, 1);
131 cv::imwrite(FLAGS_board_template_path, board_image);
132 }
133
134 std::vector<std::vector<int>> all_charuco_ids;
135 std::vector<std::vector<cv::Point2f>> all_charuco_corners;
136
137 const cv::Mat camera_matrix = calibration.CameraIntrinsics();
138 Eigen::Matrix3d eigen_camera_matrix;
139 cv::cv2eigen(camera_matrix, eigen_camera_matrix);
140
141 const cv::Mat dist_coeffs = calibration.CameraDistCoeffs();
142 LOG(INFO) << "Camera matrix " << camera_matrix;
143 LOG(INFO) << "Distortion Coefficients " << dist_coeffs;
144
145 std::optional<uint16_t> pi_number = aos::network::ParsePiNumber(FLAGS_pi);
146 CHECK(pi_number) << ": Invalid pi number " << FLAGS_pi
147 << ", failed to parse pi number";
148
149 const std::string channel =
150 absl::StrCat("/pi", std::to_string(pi_number.value()), "/camera");
151 LOG(INFO) << "Connecting to channel " << channel;
152
Ravago Jonescf453ab2020-05-06 21:14:53 -0700153 event_loop.MakeWatcher(channel, [&event_loop, &board, &all_charuco_ids,
154 &all_charuco_corners, camera_matrix,
155 dist_coeffs, eigen_camera_matrix](
156 const CameraImage &image) {
157 const aos::monotonic_clock::duration age =
158 event_loop.monotonic_now() - event_loop.context().monotonic_event_time;
159 const double age_double =
160 std::chrono::duration_cast<std::chrono::duration<double>>(age).count();
161 if (age > std::chrono::milliseconds(100)) {
162 LOG(INFO) << "Age: " << age_double << ", getting behind, skipping";
163 return;
164 }
165 // Create color image:
166 cv::Mat image_color_mat(cv::Size(image.cols(), image.rows()), CV_8UC2,
167 (void *)image.data()->data());
168 const cv::Size image_size(image.cols(), image.rows());
169 cv::Mat rgb_image(image_size, CV_8UC3);
170 cv::cvtColor(image_color_mat, rgb_image, CV_YUV2BGR_YUYV);
Austin Schuhc1f118e2020-04-11 15:50:08 -0700171
Ravago Jonescf453ab2020-05-06 21:14:53 -0700172 std::vector<int> marker_ids;
173 std::vector<std::vector<cv::Point2f>> marker_corners;
Austin Schuhc1f118e2020-04-11 15:50:08 -0700174
Ravago Jonescf453ab2020-05-06 21:14:53 -0700175 cv::aruco::detectMarkers(rgb_image, board->dictionary, marker_corners,
176 marker_ids);
Austin Schuhc1f118e2020-04-11 15:50:08 -0700177
Ravago Jonescf453ab2020-05-06 21:14:53 -0700178 std::vector<cv::Point2f> charuco_corners;
179 std::vector<int> charuco_ids;
180 // If at least one marker detected
181 if (marker_ids.size() >= FLAGS_min_targets) {
182 // Run everything twice, once with the calibration, and once without.
183 // This lets us both calibrate, and also print out the pose real time
184 // with the previous calibration.
185 cv::aruco::interpolateCornersCharuco(marker_corners, marker_ids,
186 rgb_image, board, charuco_corners,
187 charuco_ids);
Austin Schuhc1f118e2020-04-11 15:50:08 -0700188
Ravago Jonescf453ab2020-05-06 21:14:53 -0700189 std::vector<cv::Point2f> charuco_corners_with_calibration;
190 std::vector<int> charuco_ids_with_calibration;
Austin Schuhc1f118e2020-04-11 15:50:08 -0700191
Ravago Jonescf453ab2020-05-06 21:14:53 -0700192 cv::aruco::interpolateCornersCharuco(
193 marker_corners, marker_ids, rgb_image, board,
194 charuco_corners_with_calibration, charuco_ids_with_calibration,
195 camera_matrix, dist_coeffs);
Austin Schuhc1f118e2020-04-11 15:50:08 -0700196
Ravago Jonescf453ab2020-05-06 21:14:53 -0700197 cv::aruco::drawDetectedMarkers(rgb_image, marker_corners, marker_ids);
Austin Schuhc1f118e2020-04-11 15:50:08 -0700198
Ravago Jonescf453ab2020-05-06 21:14:53 -0700199 if (charuco_ids.size() >= FLAGS_min_targets) {
200 cv::aruco::drawDetectedCornersCharuco(
201 rgb_image, charuco_corners, charuco_ids, cv::Scalar(255, 0, 0));
Austin Schuhc1f118e2020-04-11 15:50:08 -0700202
Ravago Jonescf453ab2020-05-06 21:14:53 -0700203 cv::Vec3d rvec, tvec;
204 bool valid = cv::aruco::estimatePoseCharucoBoard(
205 charuco_corners_with_calibration, charuco_ids_with_calibration,
206 board, camera_matrix, dist_coeffs, rvec, tvec);
Austin Schuhc1f118e2020-04-11 15:50:08 -0700207
Ravago Jonescf453ab2020-05-06 21:14:53 -0700208 // if charuco pose is valid
209 if (valid) {
210 LOG(INFO) << std::fixed << std::setprecision(6)
211 << "Age: " << age_double << ", Pose is R:" << rvec
212 << " T:" << tvec;
213 cv::aruco::drawAxis(rgb_image, camera_matrix, dist_coeffs, rvec, tvec,
214 0.1);
Austin Schuhc1f118e2020-04-11 15:50:08 -0700215 } else {
Ravago Jonescf453ab2020-05-06 21:14:53 -0700216 LOG(INFO) << "Age: " << age_double << ", invalid pose";
Austin Schuhc1f118e2020-04-11 15:50:08 -0700217 }
Ravago Jonescf453ab2020-05-06 21:14:53 -0700218 } else {
219 LOG(INFO) << "Age: " << age_double << ", no charuco IDs.";
220 }
221 } else {
222 LOG(INFO) << "Age: " << age_double << ", no marker IDs";
223 }
Austin Schuhc1f118e2020-04-11 15:50:08 -0700224
Ravago Jonescf453ab2020-05-06 21:14:53 -0700225 cv::imshow("Display", rgb_image);
Austin Schuhc1f118e2020-04-11 15:50:08 -0700226
Ravago Jonescf453ab2020-05-06 21:14:53 -0700227 if (FLAGS_display_undistorted) {
228 cv::Mat undistorted_rgb_image(image_size, CV_8UC3);
229 cv::undistort(rgb_image, undistorted_rgb_image, camera_matrix,
230 dist_coeffs);
Austin Schuhc1f118e2020-04-11 15:50:08 -0700231
Ravago Jonescf453ab2020-05-06 21:14:53 -0700232 cv::imshow("Display undist", undistorted_rgb_image);
233 }
Austin Schuhc1f118e2020-04-11 15:50:08 -0700234
Ravago Jonescf453ab2020-05-06 21:14:53 -0700235 int keystroke = cv::waitKey(1);
236 if ((keystroke & 0xFF) == static_cast<int>('c')) {
237 if (charuco_ids.size() >= FLAGS_min_targets) {
238 all_charuco_ids.emplace_back(std::move(charuco_ids));
239 all_charuco_corners.emplace_back(std::move(charuco_corners));
240 LOG(INFO) << "Image " << all_charuco_corners.size();
241 }
Austin Schuhc1f118e2020-04-11 15:50:08 -0700242
Ravago Jonescf453ab2020-05-06 21:14:53 -0700243 if (all_charuco_ids.size() >= 50) {
244 LOG(INFO) << "Got enough images to calibrate";
245 event_loop.Exit();
246 }
247 } else if ((keystroke & 0xFF) == static_cast<int>('q')) {
248 event_loop.Exit();
249 }
250 });
Austin Schuhc1f118e2020-04-11 15:50:08 -0700251
252 event_loop.Run();
253
254 if (all_charuco_ids.size() >= 50) {
255 cv::Mat cameraMatrix, distCoeffs;
256 std::vector<cv::Mat> rvecs, tvecs;
257 cv::Mat stdDeviationsIntrinsics, stdDeviationsExtrinsics, perViewErrors;
258
259 // Set calibration flags (same than in calibrateCamera() function)
260 int calibration_flags = 0;
261 cv::Size img_size(640, 480);
262 const double reprojection_error = cv::aruco::calibrateCameraCharuco(
263 all_charuco_corners, all_charuco_ids, board, img_size, cameraMatrix,
264 distCoeffs, rvecs, tvecs, stdDeviationsIntrinsics,
265 stdDeviationsExtrinsics, perViewErrors, calibration_flags);
266 CHECK_LE(reprojection_error, 1.0) << ": Reproduction error is bad.";
267 LOG(INFO) << "Reprojection Error is " << reprojection_error;
268
269 flatbuffers::FlatBufferBuilder fbb;
270 flatbuffers::Offset<flatbuffers::String> name_offset =
271 fbb.CreateString(absl::StrFormat("pi%d", pi_number.value()));
272 flatbuffers::Offset<flatbuffers::Vector<float>> intrinsics_offset =
273 fbb.CreateVector<float>(9u, [&cameraMatrix](size_t i) {
274 return static_cast<float>(
275 reinterpret_cast<double *>(cameraMatrix.data)[i]);
276 });
277
278 flatbuffers::Offset<flatbuffers::Vector<float>>
279 distortion_coefficients_offset =
280 fbb.CreateVector<float>(5u, [&distCoeffs](size_t i) {
281 return static_cast<float>(
282 reinterpret_cast<double *>(distCoeffs.data)[i]);
283 });
284
285 sift::CameraCalibration::Builder camera_calibration_builder(fbb);
286 std::optional<uint16_t> team_number =
287 aos::network::team_number_internal::ParsePiTeamNumber(FLAGS_pi);
288 CHECK(team_number) << ": Invalid pi hostname " << FLAGS_pi
289 << ", failed to parse team number";
290
291 const aos::realtime_clock::time_point realtime_now =
292 aos::realtime_clock::now();
293 camera_calibration_builder.add_node_name(name_offset);
294 camera_calibration_builder.add_team_number(team_number.value());
295 camera_calibration_builder.add_calibration_timestamp(
296 realtime_now.time_since_epoch().count());
297 camera_calibration_builder.add_intrinsics(intrinsics_offset);
298 camera_calibration_builder.add_dist_coeffs(distortion_coefficients_offset);
299 camera_calibration_builder.add_dist_coeffs(distortion_coefficients_offset);
300 fbb.Finish(camera_calibration_builder.Finish());
301
302 aos::FlatbufferDetachedBuffer<sift::CameraCalibration> camera_calibration(
303 fbb.Release());
304 std::stringstream time_ss;
305 time_ss << realtime_now;
306
307 const std::string calibration_filename =
308 FLAGS_calibration_folder +
309 absl::StrFormat("/calibration_pi-%d-%d_%s.json", team_number.value(),
310 pi_number.value(), time_ss.str());
311
312 LOG(INFO) << calibration_filename << " -> "
Ravago Jonescf453ab2020-05-06 21:14:53 -0700313 << aos::FlatbufferToJson(camera_calibration,
314 {.multi_line = true});
Austin Schuhc1f118e2020-04-11 15:50:08 -0700315
316 aos::util::WriteStringToFileOrDie(
Ravago Jonescf453ab2020-05-06 21:14:53 -0700317 calibration_filename,
318 aos::FlatbufferToJson(camera_calibration, {.multi_line = true}));
Austin Schuhc1f118e2020-04-11 15:50:08 -0700319 } else {
320 LOG(INFO) << "Skipping calibration due to not enough images.";
321 }
322}
323
324} // namespace
325} // namespace vision
326} // namespace frc971
327
328// Quick and lightweight grayscale viewer for images
329int main(int argc, char **argv) {
330 aos::InitGoogle(&argc, &argv);
331 frc971::vision::ViewerMain();
332}