blob: 8e8acc3c2ac5fc19d8bf8eb67070bb72a954cd32 [file] [log] [blame]
Austin Schuhdcb6b362022-02-25 18:06:21 -08001#include "frc971/vision/charuco_lib.h"
Austin Schuh25837f22021-06-27 15:49:14 -07002
3#include <chrono>
4#include <functional>
Philipp Schrader790cb542023-07-05 21:06:52 -07005#include <string_view>
6
7#include "glog/logging.h"
Austin Schuh25837f22021-06-27 15:49:14 -07008#include <opencv2/core/eigen.hpp>
9#include <opencv2/highgui/highgui.hpp>
10#include <opencv2/imgproc.hpp>
Austin Schuhdcb6b362022-02-25 18:06:21 -080011
Austin Schuh25837f22021-06-27 15:49:14 -070012#include "aos/events/event_loop.h"
13#include "aos/flatbuffers.h"
14#include "aos/network/team_number.h"
15#include "frc971/control_loops/quaternion_utils.h"
Jim Ostrowski977850f2022-01-22 21:04:22 -080016#include "frc971/vision/vision_generated.h"
Austin Schuh25837f22021-06-27 15:49:14 -070017
Austin Schuh25837f22021-06-27 15:49:14 -070018DEFINE_string(board_template_path, "",
19 "If specified, write an image to the specified path for the "
20 "charuco board pattern.");
Jim Ostrowskib3cab972022-12-03 15:47:00 -080021DEFINE_bool(coarse_pattern, true, "If true, use coarse arucos; else, use fine");
Jim Ostrowski814d2812022-12-11 23:17:14 -080022DEFINE_uint32(gray_threshold, 0,
23 "If > 0, threshold image based on this grayscale value");
Jim Ostrowskib3cab972022-12-03 15:47:00 -080024DEFINE_bool(large_board, true, "If true, use the large calibration board.");
25DEFINE_uint32(
26 min_charucos, 10,
27 "The mininum number of aruco targets in charuco board required to match.");
Jim Ostrowski2f2685f2023-03-25 11:57:54 -070028DEFINE_uint32(min_id, 0, "Minimum valid charuco id");
29DEFINE_uint32(max_diamonds, 0,
30 "Maximum number of diamonds to see. Set to 0 for no limit");
31DEFINE_uint32(max_id, 15, "Maximum valid charuco id");
Jim Ostrowskib3cab972022-12-03 15:47:00 -080032DEFINE_bool(visualize, false, "Whether to visualize the resulting data.");
Jim Ostrowski814d2812022-12-11 23:17:14 -080033DEFINE_bool(
34 draw_axes, false,
35 "Whether to draw axes on the resulting data-- warning, may cause crashes.");
Austin Schuh25837f22021-06-27 15:49:14 -070036
Austin Schuhc3419862023-01-08 13:54:36 -080037DEFINE_uint32(disable_delay, 100, "Time after an issue to disable tracing at.");
38
39DECLARE_bool(enable_ftrace);
40
Austin Schuh25837f22021-06-27 15:49:14 -070041namespace frc971 {
42namespace vision {
43namespace chrono = std::chrono;
Austin Schuhea7b0142021-10-08 22:04:53 -070044using aos::monotonic_clock;
Austin Schuh25837f22021-06-27 15:49:14 -070045
46CameraCalibration::CameraCalibration(
James Kuszmaul7e958812023-02-11 15:34:31 -080047 const calibration::CameraCalibration *calibration)
48 : intrinsics_([calibration]() {
49 const cv::Mat result(3, 3, CV_32F,
50 const_cast<void *>(static_cast<const void *>(
51 calibration->intrinsics()->data())));
52 CHECK_EQ(result.total(), calibration->intrinsics()->size());
53 return result;
54 }()),
55 intrinsics_eigen_([this]() {
56 cv::Mat camera_intrinsics = intrinsics_;
57 Eigen::Matrix3d result;
58 cv::cv2eigen(camera_intrinsics, result);
59 return result;
60 }()),
61 dist_coeffs_([calibration]() {
62 const cv::Mat result(5, 1, CV_32F,
63 const_cast<void *>(static_cast<const void *>(
64 calibration->dist_coeffs()->data())));
65 CHECK_EQ(result.total(), calibration->dist_coeffs()->size());
66 return result;
67 }()) {}
Austin Schuh25837f22021-06-27 15:49:14 -070068
Austin Schuhea7b0142021-10-08 22:04:53 -070069ImageCallback::ImageCallback(
70 aos::EventLoop *event_loop, std::string_view channel,
milind-u0cb53112023-02-03 20:32:55 -080071 std::function<void(cv::Mat, monotonic_clock::time_point)> &&handle_image_fn,
72 monotonic_clock::duration max_age)
Austin Schuhea7b0142021-10-08 22:04:53 -070073 : event_loop_(event_loop),
74 server_fetcher_(
75 event_loop_->MakeFetcher<aos::message_bridge::ServerStatistics>(
76 "/aos")),
77 source_node_(aos::configuration::GetNode(
78 event_loop_->configuration(),
79 event_loop_->GetChannel<CameraImage>(channel)
80 ->source_node()
81 ->string_view())),
Austin Schuhc3419862023-01-08 13:54:36 -080082 handle_image_(std::move(handle_image_fn)),
milind-u0cb53112023-02-03 20:32:55 -080083 timer_fn_(event_loop->AddTimer([this]() { DisableTracing(); })),
84 max_age_(max_age) {
Austin Schuh25837f22021-06-27 15:49:14 -070085 event_loop_->MakeWatcher(channel, [this](const CameraImage &image) {
Austin Schuhea7b0142021-10-08 22:04:53 -070086 const monotonic_clock::time_point eof_source_node =
87 monotonic_clock::time_point(
88 chrono::nanoseconds(image.monotonic_timestamp_ns()));
Austin Schuhea7b0142021-10-08 22:04:53 -070089 chrono::nanoseconds offset{0};
90 if (source_node_ != event_loop_->node()) {
Austin Schuhee8bc1e2021-11-20 16:23:41 -080091 server_fetcher_.Fetch();
92 if (!server_fetcher_.get()) {
93 return;
94 }
95
Austin Schuhea7b0142021-10-08 22:04:53 -070096 // If we are viewing this image from another node, convert to our
97 // monotonic clock.
98 const aos::message_bridge::ServerConnection *server_connection = nullptr;
99
100 for (const aos::message_bridge::ServerConnection *connection :
101 *server_fetcher_->connections()) {
102 CHECK(connection->has_node());
103 if (connection->node()->name()->string_view() ==
104 source_node_->name()->string_view()) {
105 server_connection = connection;
106 break;
107 }
108 }
109
110 CHECK(server_connection != nullptr) << ": Failed to find client";
111 if (!server_connection->has_monotonic_offset()) {
112 VLOG(1) << "No offset yet.";
113 return;
114 }
115 offset = chrono::nanoseconds(server_connection->monotonic_offset());
116 }
117
118 const monotonic_clock::time_point eof = eof_source_node - offset;
119
Jim Ostrowski977850f2022-01-22 21:04:22 -0800120 const monotonic_clock::duration age = event_loop_->monotonic_now() - eof;
Austin Schuh25837f22021-06-27 15:49:14 -0700121 const double age_double =
122 std::chrono::duration_cast<std::chrono::duration<double>>(age).count();
milind-u0cb53112023-02-03 20:32:55 -0800123 if (age > max_age_) {
Austin Schuhc3419862023-01-08 13:54:36 -0800124 if (FLAGS_enable_ftrace) {
125 ftrace_.FormatMessage("Too late receiving image, age: %f\n",
126 age_double);
127 if (FLAGS_disable_delay > 0) {
128 if (!disabling_) {
Philipp Schradera6712522023-07-05 20:25:11 -0700129 timer_fn_->Schedule(event_loop_->monotonic_now() +
130 chrono::milliseconds(FLAGS_disable_delay));
Austin Schuhc3419862023-01-08 13:54:36 -0800131 disabling_ = true;
132 }
133 } else {
134 DisableTracing();
135 }
136 }
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800137 VLOG(2) << "Age: " << age_double << ", getting behind, skipping";
Austin Schuh25837f22021-06-27 15:49:14 -0700138 return;
139 }
140 // Create color image:
141 cv::Mat image_color_mat(cv::Size(image.cols(), image.rows()), CV_8UC2,
142 (void *)image.data()->data());
143 const cv::Size image_size(image.cols(), image.rows());
Austin Schuhac402e92023-01-08 13:56:20 -0800144 switch (format_) {
145 case Format::GRAYSCALE: {
146 ftrace_.FormatMessage("Starting yuyv->greyscale\n");
147 cv::Mat gray_image(image_size, CV_8UC3);
148 cv::cvtColor(image_color_mat, gray_image, cv::COLOR_YUV2GRAY_YUYV);
149 handle_image_(gray_image, eof);
150 } break;
151 case Format::BGR: {
152 cv::Mat rgb_image(image_size, CV_8UC3);
153 cv::cvtColor(image_color_mat, rgb_image, cv::COLOR_YUV2BGR_YUYV);
154 handle_image_(rgb_image, eof);
155 } break;
156 case Format::YUYV2: {
157 handle_image_(image_color_mat, eof);
158 };
159 }
Austin Schuh25837f22021-06-27 15:49:14 -0700160 });
161}
162
Austin Schuhc3419862023-01-08 13:54:36 -0800163void ImageCallback::DisableTracing() {
164 disabling_ = false;
165 ftrace_.TurnOffOrDie();
166}
167
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800168void CharucoExtractor::SetupTargetData() {
Jim Ostrowski814d2812022-12-11 23:17:14 -0800169 marker_length_ = 0.146;
170 square_length_ = 0.2;
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800171
172 // Only charuco board has a board associated with it
173 board_ = static_cast<cv::Ptr<cv::aruco::CharucoBoard>>(NULL);
174
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800175 if (target_type_ == TargetType::kCharuco ||
176 target_type_ == TargetType::kAruco) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800177 dictionary_ = cv::aruco::getPredefinedDictionary(
178 FLAGS_large_board ? cv::aruco::DICT_5X5_250 : cv::aruco::DICT_6X6_250);
179
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800180 if (target_type_ == TargetType::kCharuco) {
Jim Ostrowski814d2812022-12-11 23:17:14 -0800181 LOG(INFO) << "Using " << (FLAGS_large_board ? "large" : "small")
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800182 << " charuco board with "
183 << (FLAGS_coarse_pattern ? "coarse" : "fine") << " pattern";
184 board_ =
185 (FLAGS_large_board
186 ? (FLAGS_coarse_pattern ? cv::aruco::CharucoBoard::create(
187 12, 9, 0.06, 0.04666, dictionary_)
188 : cv::aruco::CharucoBoard::create(
189 25, 18, 0.03, 0.0233, dictionary_))
190 : (FLAGS_coarse_pattern ? cv::aruco::CharucoBoard::create(
191 7, 5, 0.04, 0.025, dictionary_)
192 // TODO(jim): Need to figure out what
193 // size is for small board, fine pattern
194 : cv::aruco::CharucoBoard::create(
195 7, 5, 0.03, 0.0233, dictionary_)));
196 if (!FLAGS_board_template_path.empty()) {
197 cv::Mat board_image;
198 board_->draw(cv::Size(600, 500), board_image, 10, 1);
199 cv::imwrite(FLAGS_board_template_path, board_image);
200 }
201 }
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800202 } else if (target_type_ == TargetType::kCharucoDiamond) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800203 marker_length_ = 0.15;
Jim Ostrowski814d2812022-12-11 23:17:14 -0800204 square_length_ = 0.2;
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800205 dictionary_ = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_4X4_250);
Jim Ostrowski2be78e32023-03-25 11:57:54 -0700206 } else if (target_type_ == TargetType::kAprilTag) {
207 marker_length_ = 0.1016;
208 square_length_ = 0.1524;
209 dictionary_ =
210 cv::aruco::getPredefinedDictionary(cv::aruco::DICT_APRILTAG_16h5);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800211 } else {
212 // Bail out if it's not a supported target
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800213 LOG(FATAL) << "Target type undefined: "
214 << static_cast<uint8_t>(target_type_);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800215 }
216}
217
218void CharucoExtractor::DrawTargetPoses(cv::Mat rgb_image,
219 std::vector<cv::Vec3d> rvecs,
220 std::vector<cv::Vec3d> tvecs) {
221 const Eigen::Matrix<double, 3, 4> camera_projection =
222 Eigen::Matrix<double, 3, 4>::Identity();
223
224 int x_coord = 10;
225 int y_coord = 0;
226 // draw axis for each marker
227 for (uint i = 0; i < rvecs.size(); i++) {
228 Eigen::Vector3d rvec_eigen, tvec_eigen;
229 cv::cv2eigen(rvecs[i], rvec_eigen);
230 cv::cv2eigen(tvecs[i], tvec_eigen);
231
232 Eigen::Quaternion<double> rotation(
233 frc971::controls::ToQuaternionFromRotationVector(rvec_eigen));
234 Eigen::Translation3d translation(tvec_eigen);
235
236 const Eigen::Affine3d board_to_camera = translation * rotation;
237
James Kuszmaul7e958812023-02-11 15:34:31 -0800238 Eigen::Vector3d result = calibration_.CameraIntrinsicsEigen() *
239 camera_projection * board_to_camera *
240 Eigen::Vector3d::Zero();
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800241
242 // Found that drawAxis hangs if you try to draw with z values too
243 // small (trying to draw axes at inifinity)
Jim Ostrowski814d2812022-12-11 23:17:14 -0800244 // TODO<Jim>: Either track this down or reimplement drawAxes
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800245 if (result.z() < 0.01) {
246 LOG(INFO) << "Skipping, due to z value too small: " << result.z();
Jim Ostrowski814d2812022-12-11 23:17:14 -0800247 } else if (FLAGS_draw_axes == true) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800248 result /= result.z();
Jim Ostrowski2be78e32023-03-25 11:57:54 -0700249 if (target_type_ == TargetType::kCharuco ||
250 target_type_ == TargetType::kAprilTag) {
Austin Schuhbffbe8b2023-11-22 21:32:05 -0800251 cv::drawFrameAxes(rgb_image, calibration_.CameraIntrinsics(),
252 calibration_.CameraDistCoeffs(), rvecs[i], tvecs[i],
253 square_length_);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800254 } else {
James Kuszmaul7e958812023-02-11 15:34:31 -0800255 cv::drawFrameAxes(rgb_image, calibration_.CameraIntrinsics(),
256 calibration_.CameraDistCoeffs(), rvecs[i], tvecs[i],
Jim Ostrowski2be78e32023-03-25 11:57:54 -0700257 square_length_);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800258 }
259 }
260 std::stringstream ss;
261 ss << "tvec[" << i << "] = " << tvecs[i];
262 y_coord += 25;
263 cv::putText(rgb_image, ss.str(), cv::Point(x_coord, y_coord),
264 cv::FONT_HERSHEY_PLAIN, 1.0, cv::Scalar(255, 255, 255));
265 ss.str("");
266 ss << "rvec[" << i << "] = " << rvecs[i];
267 y_coord += 25;
268 cv::putText(rgb_image, ss.str(), cv::Point(x_coord, y_coord),
269 cv::FONT_HERSHEY_PLAIN, 1.0, cv::Scalar(255, 255, 255));
270 }
271}
272
273void CharucoExtractor::PackPoseResults(
274 std::vector<cv::Vec3d> &rvecs, std::vector<cv::Vec3d> &tvecs,
275 std::vector<Eigen::Vector3d> *rvecs_eigen,
276 std::vector<Eigen::Vector3d> *tvecs_eigen) {
277 for (cv::Vec3d rvec : rvecs) {
278 Eigen::Vector3d rvec_eigen = Eigen::Vector3d::Zero();
279 cv::cv2eigen(rvec, rvec_eigen);
280 rvecs_eigen->emplace_back(rvec_eigen);
281 }
282
283 for (cv::Vec3d tvec : tvecs) {
284 Eigen::Vector3d tvec_eigen = Eigen::Vector3d::Zero();
285 cv::cv2eigen(tvec, tvec_eigen);
286 tvecs_eigen->emplace_back(tvec_eigen);
287 }
288}
289
Austin Schuh25837f22021-06-27 15:49:14 -0700290CharucoExtractor::CharucoExtractor(
Jim Ostrowski2f2685f2023-03-25 11:57:54 -0700291 const calibration::CameraCalibration *calibration,
292 const TargetType target_type)
293 : event_loop_(nullptr),
294 target_type_(target_type),
295 calibration_(CHECK_NOTNULL(calibration)) {
296 VLOG(2) << "Configuring CharucoExtractor without event_loop";
297 SetupTargetData();
298 VLOG(2) << "Camera matrix:\n" << calibration_.CameraIntrinsics();
299 VLOG(2) << "Distortion Coefficients:\n" << calibration_.CameraDistCoeffs();
300}
301
302CharucoExtractor::CharucoExtractor(
James Kuszmaul7e958812023-02-11 15:34:31 -0800303 aos::EventLoop *event_loop,
Jim Ostrowski2f2685f2023-03-25 11:57:54 -0700304 const calibration::CameraCalibration *calibration,
305 const TargetType target_type, std::string_view image_channel,
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800306 std::function<void(cv::Mat, monotonic_clock::time_point,
307 std::vector<cv::Vec4i>,
308 std::vector<std::vector<cv::Point2f>>, bool,
309 std::vector<Eigen::Vector3d>,
310 std::vector<Eigen::Vector3d>)> &&handle_charuco_fn)
Austin Schuhea7b0142021-10-08 22:04:53 -0700311 : event_loop_(event_loop),
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800312 target_type_(target_type),
313 image_channel_(image_channel),
James Kuszmaul7e958812023-02-11 15:34:31 -0800314 calibration_(CHECK_NOTNULL(calibration)),
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800315 handle_charuco_(std::move(handle_charuco_fn)) {
316 SetupTargetData();
Austin Schuh25837f22021-06-27 15:49:14 -0700317
James Kuszmaul7e958812023-02-11 15:34:31 -0800318 LOG(INFO) << "Camera matrix " << calibration_.CameraIntrinsics();
319 LOG(INFO) << "Distortion Coefficients " << calibration_.CameraDistCoeffs();
Austin Schuh25837f22021-06-27 15:49:14 -0700320
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800321 LOG(INFO) << "Connecting to channel " << image_channel_;
Austin Schuh25837f22021-06-27 15:49:14 -0700322}
323
Austin Schuhea7b0142021-10-08 22:04:53 -0700324void CharucoExtractor::HandleImage(cv::Mat rgb_image,
325 const monotonic_clock::time_point eof) {
Jim Ostrowski2f2685f2023-03-25 11:57:54 -0700326 // Set up the variables we'll use in the callback function
327 bool valid = false;
328 // ids and corners for final, refined board / marker detections
329 // Using Vec4i type since it supports Charuco Diamonds
330 // And overloading it using 1st int in Vec4i for others target types
331 std::vector<cv::Vec4i> result_ids;
332 std::vector<std::vector<cv::Point2f>> result_corners;
333
334 // Return a list of poses; for Charuco Board there will be just one
335 std::vector<Eigen::Vector3d> rvecs_eigen;
336 std::vector<Eigen::Vector3d> tvecs_eigen;
337 ProcessImage(rgb_image, eof, event_loop_->monotonic_now(), result_ids,
338 result_corners, valid, rvecs_eigen, tvecs_eigen);
339
340 handle_charuco_(rgb_image, eof, result_ids, result_corners, valid,
341 rvecs_eigen, tvecs_eigen);
342}
343
344void CharucoExtractor::ProcessImage(
345 cv::Mat rgb_image, const monotonic_clock::time_point eof,
346 const monotonic_clock::time_point current_time,
347 std::vector<cv::Vec4i> &result_ids,
348 std::vector<std::vector<cv::Point2f>> &result_corners, bool &valid,
349 std::vector<Eigen::Vector3d> &rvecs_eigen,
350 std::vector<Eigen::Vector3d> &tvecs_eigen) {
Austin Schuhea7b0142021-10-08 22:04:53 -0700351 const double age_double =
Jim Ostrowski2f2685f2023-03-25 11:57:54 -0700352 std::chrono::duration_cast<std::chrono::duration<double>>(current_time -
353 eof)
Austin Schuhea7b0142021-10-08 22:04:53 -0700354 .count();
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800355
Jim Ostrowski814d2812022-12-11 23:17:14 -0800356 // Have found this useful if there is blurry / noisy images
357 if (FLAGS_gray_threshold > 0) {
358 cv::Mat gray;
359 cv::cvtColor(rgb_image, gray, cv::COLOR_BGR2GRAY);
360
361 cv::Mat thresh;
362 cv::threshold(gray, thresh, FLAGS_gray_threshold, 255, cv::THRESH_BINARY);
363 cv::cvtColor(thresh, rgb_image, cv::COLOR_GRAY2RGB);
364 }
365
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800366 // ids and corners for initial aruco marker detections
Austin Schuh25837f22021-06-27 15:49:14 -0700367 std::vector<int> marker_ids;
368 std::vector<std::vector<cv::Point2f>> marker_corners;
369
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800370 // Do initial marker detection; this is the same for all target types
371 cv::aruco::detectMarkers(rgb_image, dictionary_, marker_corners, marker_ids);
372 cv::aruco::drawDetectedMarkers(rgb_image, marker_corners, marker_ids);
Austin Schuhea7b0142021-10-08 22:04:53 -0700373
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800374 VLOG(2) << "Handle Image, with target type = "
375 << static_cast<uint8_t>(target_type_) << " and " << marker_ids.size()
376 << " markers detected initially";
Austin Schuh25837f22021-06-27 15:49:14 -0700377
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800378 if (marker_ids.size() == 0) {
379 VLOG(2) << "Didn't find any markers";
380 } else {
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800381 if (target_type_ == TargetType::kCharuco) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800382 std::vector<int> charuco_ids;
383 std::vector<cv::Point2f> charuco_corners;
Austin Schuh25837f22021-06-27 15:49:14 -0700384
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800385 // If enough aruco markers detected for the Charuco board
386 if (marker_ids.size() >= FLAGS_min_charucos) {
387 // Run everything twice, once with the calibration, and once
388 // without. This lets us both collect data to calibrate the
389 // intrinsics of the camera (to determine the intrinsics from
390 // multiple samples), and also to use data from a previous/stored
391 // calibration to determine a more accurate pose in real time (used
392 // for extrinsics calibration)
393 cv::aruco::interpolateCornersCharuco(marker_corners, marker_ids,
394 rgb_image, board_, charuco_corners,
395 charuco_ids);
Austin Schuh25837f22021-06-27 15:49:14 -0700396
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800397 std::vector<cv::Point2f> charuco_corners_with_calibration;
398 std::vector<int> charuco_ids_with_calibration;
Austin Schuh25837f22021-06-27 15:49:14 -0700399
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800400 // This call uses a previous intrinsic calibration to get more
401 // accurate marker locations, for a better pose estimate
402 cv::aruco::interpolateCornersCharuco(
403 marker_corners, marker_ids, rgb_image, board_,
404 charuco_corners_with_calibration, charuco_ids_with_calibration,
James Kuszmaul7e958812023-02-11 15:34:31 -0800405 calibration_.CameraIntrinsics(), calibration_.CameraDistCoeffs());
Austin Schuh25837f22021-06-27 15:49:14 -0700406
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800407 if (charuco_ids.size() >= FLAGS_min_charucos) {
408 cv::aruco::drawDetectedCornersCharuco(
409 rgb_image, charuco_corners, charuco_ids, cv::Scalar(255, 0, 0));
Austin Schuh25837f22021-06-27 15:49:14 -0700410
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800411 cv::Vec3d rvec, tvec;
412 valid = cv::aruco::estimatePoseCharucoBoard(
413 charuco_corners_with_calibration, charuco_ids_with_calibration,
James Kuszmaul7e958812023-02-11 15:34:31 -0800414 board_, calibration_.CameraIntrinsics(),
415 calibration_.CameraDistCoeffs(), rvec, tvec);
Austin Schuh25837f22021-06-27 15:49:14 -0700416
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800417 // if charuco pose is valid, return pose, with ids and corners
418 if (valid) {
419 std::vector<cv::Vec3d> rvecs, tvecs;
420 rvecs.emplace_back(rvec);
421 tvecs.emplace_back(tvec);
422 DrawTargetPoses(rgb_image, rvecs, tvecs);
Austin Schuh25837f22021-06-27 15:49:14 -0700423
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800424 PackPoseResults(rvecs, tvecs, &rvecs_eigen, &tvecs_eigen);
425 // Store the corners without calibration, since we use them to
426 // do calibration
427 result_corners.emplace_back(charuco_corners);
428 for (auto id : charuco_ids) {
429 result_ids.emplace_back(cv::Vec4i{id, 0, 0, 0});
430 }
431 } else {
432 VLOG(2) << "Age: " << age_double << ", invalid charuco board pose";
433 }
Jim Ostrowski634b2652022-03-04 02:10:53 -0800434 } else {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800435 VLOG(2) << "Age: " << age_double << ", not enough charuco IDs, got "
436 << charuco_ids.size() << ", needed " << FLAGS_min_charucos;
Jim Ostrowski634b2652022-03-04 02:10:53 -0800437 }
Austin Schuh25837f22021-06-27 15:49:14 -0700438 } else {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800439 VLOG(2) << "Age: " << age_double
440 << ", not enough marker IDs for charuco board, got "
441 << marker_ids.size() << ", needed " << FLAGS_min_charucos;
442 }
Jim Ostrowski2be78e32023-03-25 11:57:54 -0700443 } else if (target_type_ == TargetType::kAruco ||
444 target_type_ == TargetType::kAprilTag) {
milind-u09fb1252023-01-28 19:21:41 -0800445 // estimate pose for arucos doesn't return valid, so marking true
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800446 valid = true;
447 std::vector<cv::Vec3d> rvecs, tvecs;
James Kuszmaul7e958812023-02-11 15:34:31 -0800448 cv::aruco::estimatePoseSingleMarkers(
449 marker_corners, square_length_, calibration_.CameraIntrinsics(),
450 calibration_.CameraDistCoeffs(), rvecs, tvecs);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800451 DrawTargetPoses(rgb_image, rvecs, tvecs);
452
453 PackPoseResults(rvecs, tvecs, &rvecs_eigen, &tvecs_eigen);
454 for (uint i = 0; i < marker_ids.size(); i++) {
455 result_ids.emplace_back(cv::Vec4i{marker_ids[i], 0, 0, 0});
456 }
457 result_corners = marker_corners;
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800458 } else if (target_type_ == TargetType::kCharucoDiamond) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800459 // Extract the diamonds associated with the markers
460 std::vector<cv::Vec4i> diamond_ids;
461 std::vector<std::vector<cv::Point2f>> diamond_corners;
462 cv::aruco::detectCharucoDiamond(rgb_image, marker_corners, marker_ids,
463 square_length_ / marker_length_,
464 diamond_corners, diamond_ids);
465
Jim Ostrowski2f2685f2023-03-25 11:57:54 -0700466 // Check that we have an acceptable number of diamonds detected.
467 // Should be at least one, and no more than FLAGS_max_diamonds.
468 // Different calibration routines will require different values for this
469 if (diamond_ids.size() > 0 &&
470 (FLAGS_max_diamonds == 0 ||
471 diamond_ids.size() <= FLAGS_max_diamonds)) {
472 // TODO<Jim>: Could probably make this check more general than
473 // requiring range of ids
Jim Ostrowskic7d90102023-03-09 14:47:25 -0800474 bool all_valid_ids = true;
475 for (uint i = 0; i < 4; i++) {
476 uint id = diamond_ids[0][i];
477 if ((id < FLAGS_min_id) || (id > FLAGS_max_id)) {
478 all_valid_ids = false;
479 LOG(INFO) << "Got invalid charuco id: " << id;
480 }
481 }
482 if (all_valid_ids) {
483 cv::aruco::drawDetectedDiamonds(rgb_image, diamond_corners,
484 diamond_ids);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800485
Jim Ostrowski2f2685f2023-03-25 11:57:54 -0700486 // estimate pose for diamonds doesn't return valid, so marking
487 // true
Jim Ostrowskic7d90102023-03-09 14:47:25 -0800488 valid = true;
489 std::vector<cv::Vec3d> rvecs, tvecs;
490 cv::aruco::estimatePoseSingleMarkers(
491 diamond_corners, square_length_, calibration_.CameraIntrinsics(),
492 calibration_.CameraDistCoeffs(), rvecs, tvecs);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800493
Jim Ostrowski2f2685f2023-03-25 11:57:54 -0700494 DrawTargetPoses(rgb_image, rvecs, tvecs);
Jim Ostrowskic7d90102023-03-09 14:47:25 -0800495 PackPoseResults(rvecs, tvecs, &rvecs_eigen, &tvecs_eigen);
496 result_ids = diamond_ids;
497 result_corners = diamond_corners;
498 } else {
499 LOG(INFO) << "Not all charuco ids were valid, so skipping";
500 }
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800501 } else {
Jim Ostrowskic7d90102023-03-09 14:47:25 -0800502 if (diamond_ids.size() == 0) {
503 // OK to not see any markers sometimes
Jim Ostrowski2f2685f2023-03-25 11:57:54 -0700504 VLOG(2) << "Found aruco markers, but no valid charuco diamond "
505 "targets";
Jim Ostrowskic7d90102023-03-09 14:47:25 -0800506 } else {
Jim Ostrowski2f2685f2023-03-25 11:57:54 -0700507 VLOG(2) << "Found too many number of diamond markers, which likely "
508 "means false positives were detected: "
509 << diamond_ids.size() << " > " << FLAGS_max_diamonds;
Jim Ostrowskic7d90102023-03-09 14:47:25 -0800510 }
Austin Schuh25837f22021-06-27 15:49:14 -0700511 }
512 } else {
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800513 LOG(FATAL) << "Unknown target type: "
514 << static_cast<uint8_t>(target_type_);
Austin Schuh25837f22021-06-27 15:49:14 -0700515 }
Austin Schuh25837f22021-06-27 15:49:14 -0700516 }
Austin Schuh25837f22021-06-27 15:49:14 -0700517}
518
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800519flatbuffers::Offset<foxglove::ImageAnnotations> BuildAnnotations(
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800520 flatbuffers::FlatBufferBuilder *fbb,
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800521 const aos::monotonic_clock::time_point monotonic_now,
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800522 const std::vector<std::vector<cv::Point2f>> &corners,
523 const std::vector<double> rgba_color, const double thickness,
524 const foxglove::PointsAnnotationType line_type) {
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800525 std::vector<flatbuffers::Offset<foxglove::PointsAnnotation>> rectangles;
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800526 for (const std::vector<cv::Point2f> &rectangle : corners) {
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800527 rectangles.push_back(BuildPointsAnnotation(
528 fbb, monotonic_now, rectangle, rgba_color, thickness, line_type));
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800529 }
530
531 const auto rectangles_offset = fbb->CreateVector(rectangles);
532 foxglove::ImageAnnotations::Builder annotation_builder(*fbb);
533 annotation_builder.add_points(rectangles_offset);
534 return annotation_builder.Finish();
535}
536
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800537flatbuffers::Offset<foxglove::PointsAnnotation> BuildPointsAnnotation(
538 flatbuffers::FlatBufferBuilder *fbb,
539 const aos::monotonic_clock::time_point monotonic_now,
540 const std::vector<cv::Point2f> &corners,
541 const std::vector<double> rgba_color, const double thickness,
542 const foxglove::PointsAnnotationType line_type) {
543 const struct timespec now_t = aos::time::to_timespec(monotonic_now);
544 foxglove::Time time{static_cast<uint32_t>(now_t.tv_sec),
545 static_cast<uint32_t>(now_t.tv_nsec)};
546 const flatbuffers::Offset<foxglove::Color> color_offset =
547 foxglove::CreateColor(*fbb, rgba_color[0], rgba_color[1], rgba_color[2],
548 rgba_color[3]);
549 std::vector<flatbuffers::Offset<foxglove::Point2>> points_offsets;
550 for (const cv::Point2f &point : corners) {
551 points_offsets.push_back(foxglove::CreatePoint2(*fbb, point.x, point.y));
552 }
553 const flatbuffers::Offset<
554 flatbuffers::Vector<flatbuffers::Offset<foxglove::Point2>>>
555 points_offset = fbb->CreateVector(points_offsets);
556 std::vector<flatbuffers::Offset<foxglove::Color>> color_offsets(
557 points_offsets.size(), color_offset);
558 auto colors_offset = fbb->CreateVector(color_offsets);
559 foxglove::PointsAnnotation::Builder points_builder(*fbb);
560 points_builder.add_timestamp(&time);
561 points_builder.add_type(line_type);
562 points_builder.add_points(points_offset);
563 points_builder.add_outline_color(color_offset);
564 points_builder.add_outline_colors(colors_offset);
565 points_builder.add_thickness(thickness);
566
567 return points_builder.Finish();
568}
569
James Kuszmauld6199be2023-02-11 19:56:28 -0800570TargetType TargetTypeFromString(std::string_view str) {
571 if (str == "aruco") {
572 return TargetType::kAruco;
573 } else if (str == "charuco") {
574 return TargetType::kCharuco;
575 } else if (str == "charuco_diamond") {
576 return TargetType::kCharucoDiamond;
Jim Ostrowski2be78e32023-03-25 11:57:54 -0700577 } else if (str == "apriltag") {
578 return TargetType::kAprilTag;
James Kuszmauld6199be2023-02-11 19:56:28 -0800579 } else {
580 LOG(FATAL) << "Unknown target type: " << str
Jim Ostrowski2be78e32023-03-25 11:57:54 -0700581 << ", expected: apriltag|aruco|charuco|charuco_diamond";
James Kuszmauld6199be2023-02-11 19:56:28 -0800582 }
583}
584
585std::ostream &operator<<(std::ostream &os, TargetType target_type) {
586 switch (target_type) {
587 case TargetType::kAruco:
588 os << "aruco";
589 break;
590 case TargetType::kCharuco:
591 os << "charuco";
592 break;
593 case TargetType::kCharucoDiamond:
594 os << "charuco_diamond";
595 break;
Jim Ostrowski2be78e32023-03-25 11:57:54 -0700596 case TargetType::kAprilTag:
597 os << "apriltag";
598 break;
James Kuszmauld6199be2023-02-11 19:56:28 -0800599 }
600 return os;
601}
602
Austin Schuh25837f22021-06-27 15:49:14 -0700603} // namespace vision
604} // namespace frc971