blob: 89ebe197ea0ff396afe1e164018476fd1680710d [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>
Austin Schuh25837f22021-06-27 15:49:14 -07005#include <opencv2/core/eigen.hpp>
6#include <opencv2/highgui/highgui.hpp>
7#include <opencv2/imgproc.hpp>
Austin Schuhdcb6b362022-02-25 18:06:21 -08008#include <string_view>
9
Austin Schuh25837f22021-06-27 15:49:14 -070010#include "aos/events/event_loop.h"
11#include "aos/flatbuffers.h"
12#include "aos/network/team_number.h"
13#include "frc971/control_loops/quaternion_utils.h"
Jim Ostrowski977850f2022-01-22 21:04:22 -080014#include "frc971/vision/vision_generated.h"
Austin Schuh25837f22021-06-27 15:49:14 -070015#include "glog/logging.h"
Austin Schuh25837f22021-06-27 15:49:14 -070016
Austin Schuh25837f22021-06-27 15:49:14 -070017DEFINE_string(board_template_path, "",
18 "If specified, write an image to the specified path for the "
19 "charuco board pattern.");
Jim Ostrowskib3cab972022-12-03 15:47:00 -080020DEFINE_bool(coarse_pattern, true, "If true, use coarse arucos; else, use fine");
Jim Ostrowski814d2812022-12-11 23:17:14 -080021DEFINE_uint32(gray_threshold, 0,
22 "If > 0, threshold image based on this grayscale value");
Jim Ostrowskib3cab972022-12-03 15:47:00 -080023DEFINE_bool(large_board, true, "If true, use the large calibration board.");
24DEFINE_uint32(
25 min_charucos, 10,
26 "The mininum number of aruco targets in charuco board required to match.");
Jim Ostrowskic7d90102023-03-09 14:47:25 -080027DEFINE_uint32(min_id, 12, "Minimum valid charuco id");
28DEFINE_uint32(max_id, 15, "Minimum valid charuco id");
Jim Ostrowskib3cab972022-12-03 15:47:00 -080029DEFINE_bool(visualize, false, "Whether to visualize the resulting data.");
Jim Ostrowski814d2812022-12-11 23:17:14 -080030DEFINE_bool(
31 draw_axes, false,
32 "Whether to draw axes on the resulting data-- warning, may cause crashes.");
Austin Schuh25837f22021-06-27 15:49:14 -070033
Austin Schuhc3419862023-01-08 13:54:36 -080034DEFINE_uint32(disable_delay, 100, "Time after an issue to disable tracing at.");
35
36DECLARE_bool(enable_ftrace);
37
Austin Schuh25837f22021-06-27 15:49:14 -070038namespace frc971 {
39namespace vision {
40namespace chrono = std::chrono;
Austin Schuhea7b0142021-10-08 22:04:53 -070041using aos::monotonic_clock;
Austin Schuh25837f22021-06-27 15:49:14 -070042
43CameraCalibration::CameraCalibration(
James Kuszmaul7e958812023-02-11 15:34:31 -080044 const calibration::CameraCalibration *calibration)
45 : intrinsics_([calibration]() {
46 const cv::Mat result(3, 3, CV_32F,
47 const_cast<void *>(static_cast<const void *>(
48 calibration->intrinsics()->data())));
49 CHECK_EQ(result.total(), calibration->intrinsics()->size());
50 return result;
51 }()),
52 intrinsics_eigen_([this]() {
53 cv::Mat camera_intrinsics = intrinsics_;
54 Eigen::Matrix3d result;
55 cv::cv2eigen(camera_intrinsics, result);
56 return result;
57 }()),
58 dist_coeffs_([calibration]() {
59 const cv::Mat result(5, 1, CV_32F,
60 const_cast<void *>(static_cast<const void *>(
61 calibration->dist_coeffs()->data())));
62 CHECK_EQ(result.total(), calibration->dist_coeffs()->size());
63 return result;
64 }()) {}
Austin Schuh25837f22021-06-27 15:49:14 -070065
Austin Schuhea7b0142021-10-08 22:04:53 -070066ImageCallback::ImageCallback(
67 aos::EventLoop *event_loop, std::string_view channel,
milind-u0cb53112023-02-03 20:32:55 -080068 std::function<void(cv::Mat, monotonic_clock::time_point)> &&handle_image_fn,
69 monotonic_clock::duration max_age)
Austin Schuhea7b0142021-10-08 22:04:53 -070070 : event_loop_(event_loop),
71 server_fetcher_(
72 event_loop_->MakeFetcher<aos::message_bridge::ServerStatistics>(
73 "/aos")),
74 source_node_(aos::configuration::GetNode(
75 event_loop_->configuration(),
76 event_loop_->GetChannel<CameraImage>(channel)
77 ->source_node()
78 ->string_view())),
Austin Schuhc3419862023-01-08 13:54:36 -080079 handle_image_(std::move(handle_image_fn)),
milind-u0cb53112023-02-03 20:32:55 -080080 timer_fn_(event_loop->AddTimer([this]() { DisableTracing(); })),
81 max_age_(max_age) {
Austin Schuh25837f22021-06-27 15:49:14 -070082 event_loop_->MakeWatcher(channel, [this](const CameraImage &image) {
Austin Schuhea7b0142021-10-08 22:04:53 -070083 const monotonic_clock::time_point eof_source_node =
84 monotonic_clock::time_point(
85 chrono::nanoseconds(image.monotonic_timestamp_ns()));
Austin Schuhea7b0142021-10-08 22:04:53 -070086 chrono::nanoseconds offset{0};
87 if (source_node_ != event_loop_->node()) {
Austin Schuhee8bc1e2021-11-20 16:23:41 -080088 server_fetcher_.Fetch();
89 if (!server_fetcher_.get()) {
90 return;
91 }
92
Austin Schuhea7b0142021-10-08 22:04:53 -070093 // If we are viewing this image from another node, convert to our
94 // monotonic clock.
95 const aos::message_bridge::ServerConnection *server_connection = nullptr;
96
97 for (const aos::message_bridge::ServerConnection *connection :
98 *server_fetcher_->connections()) {
99 CHECK(connection->has_node());
100 if (connection->node()->name()->string_view() ==
101 source_node_->name()->string_view()) {
102 server_connection = connection;
103 break;
104 }
105 }
106
107 CHECK(server_connection != nullptr) << ": Failed to find client";
108 if (!server_connection->has_monotonic_offset()) {
109 VLOG(1) << "No offset yet.";
110 return;
111 }
112 offset = chrono::nanoseconds(server_connection->monotonic_offset());
113 }
114
115 const monotonic_clock::time_point eof = eof_source_node - offset;
116
Jim Ostrowski977850f2022-01-22 21:04:22 -0800117 const monotonic_clock::duration age = event_loop_->monotonic_now() - eof;
Austin Schuh25837f22021-06-27 15:49:14 -0700118 const double age_double =
119 std::chrono::duration_cast<std::chrono::duration<double>>(age).count();
milind-u0cb53112023-02-03 20:32:55 -0800120 if (age > max_age_) {
Austin Schuhc3419862023-01-08 13:54:36 -0800121 if (FLAGS_enable_ftrace) {
122 ftrace_.FormatMessage("Too late receiving image, age: %f\n",
123 age_double);
124 if (FLAGS_disable_delay > 0) {
125 if (!disabling_) {
126 timer_fn_->Setup(event_loop_->monotonic_now() +
127 chrono::milliseconds(FLAGS_disable_delay));
128 disabling_ = true;
129 }
130 } else {
131 DisableTracing();
132 }
133 }
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800134 VLOG(2) << "Age: " << age_double << ", getting behind, skipping";
Austin Schuh25837f22021-06-27 15:49:14 -0700135 return;
136 }
137 // Create color image:
138 cv::Mat image_color_mat(cv::Size(image.cols(), image.rows()), CV_8UC2,
139 (void *)image.data()->data());
140 const cv::Size image_size(image.cols(), image.rows());
Austin Schuhac402e92023-01-08 13:56:20 -0800141 switch (format_) {
142 case Format::GRAYSCALE: {
143 ftrace_.FormatMessage("Starting yuyv->greyscale\n");
144 cv::Mat gray_image(image_size, CV_8UC3);
145 cv::cvtColor(image_color_mat, gray_image, cv::COLOR_YUV2GRAY_YUYV);
146 handle_image_(gray_image, eof);
147 } break;
148 case Format::BGR: {
149 cv::Mat rgb_image(image_size, CV_8UC3);
150 cv::cvtColor(image_color_mat, rgb_image, cv::COLOR_YUV2BGR_YUYV);
151 handle_image_(rgb_image, eof);
152 } break;
153 case Format::YUYV2: {
154 handle_image_(image_color_mat, eof);
155 };
156 }
Austin Schuh25837f22021-06-27 15:49:14 -0700157 });
158}
159
Austin Schuhc3419862023-01-08 13:54:36 -0800160void ImageCallback::DisableTracing() {
161 disabling_ = false;
162 ftrace_.TurnOffOrDie();
163}
164
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800165void CharucoExtractor::SetupTargetData() {
Jim Ostrowski814d2812022-12-11 23:17:14 -0800166 marker_length_ = 0.146;
167 square_length_ = 0.2;
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800168
169 // Only charuco board has a board associated with it
170 board_ = static_cast<cv::Ptr<cv::aruco::CharucoBoard>>(NULL);
171
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800172 if (target_type_ == TargetType::kCharuco ||
173 target_type_ == TargetType::kAruco) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800174 dictionary_ = cv::aruco::getPredefinedDictionary(
175 FLAGS_large_board ? cv::aruco::DICT_5X5_250 : cv::aruco::DICT_6X6_250);
176
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800177 if (target_type_ == TargetType::kCharuco) {
Jim Ostrowski814d2812022-12-11 23:17:14 -0800178 LOG(INFO) << "Using " << (FLAGS_large_board ? "large" : "small")
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800179 << " charuco board with "
180 << (FLAGS_coarse_pattern ? "coarse" : "fine") << " pattern";
181 board_ =
182 (FLAGS_large_board
183 ? (FLAGS_coarse_pattern ? cv::aruco::CharucoBoard::create(
184 12, 9, 0.06, 0.04666, dictionary_)
185 : cv::aruco::CharucoBoard::create(
186 25, 18, 0.03, 0.0233, dictionary_))
187 : (FLAGS_coarse_pattern ? cv::aruco::CharucoBoard::create(
188 7, 5, 0.04, 0.025, dictionary_)
189 // TODO(jim): Need to figure out what
190 // size is for small board, fine pattern
191 : cv::aruco::CharucoBoard::create(
192 7, 5, 0.03, 0.0233, dictionary_)));
193 if (!FLAGS_board_template_path.empty()) {
194 cv::Mat board_image;
195 board_->draw(cv::Size(600, 500), board_image, 10, 1);
196 cv::imwrite(FLAGS_board_template_path, board_image);
197 }
198 }
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800199 } else if (target_type_ == TargetType::kCharucoDiamond) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800200 marker_length_ = 0.15;
Jim Ostrowski814d2812022-12-11 23:17:14 -0800201 square_length_ = 0.2;
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800202 dictionary_ = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_4X4_250);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800203 } else {
204 // Bail out if it's not a supported target
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800205 LOG(FATAL) << "Target type undefined: "
206 << static_cast<uint8_t>(target_type_);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800207 }
208}
209
210void CharucoExtractor::DrawTargetPoses(cv::Mat rgb_image,
211 std::vector<cv::Vec3d> rvecs,
212 std::vector<cv::Vec3d> tvecs) {
213 const Eigen::Matrix<double, 3, 4> camera_projection =
214 Eigen::Matrix<double, 3, 4>::Identity();
215
216 int x_coord = 10;
217 int y_coord = 0;
218 // draw axis for each marker
219 for (uint i = 0; i < rvecs.size(); i++) {
220 Eigen::Vector3d rvec_eigen, tvec_eigen;
221 cv::cv2eigen(rvecs[i], rvec_eigen);
222 cv::cv2eigen(tvecs[i], tvec_eigen);
223
224 Eigen::Quaternion<double> rotation(
225 frc971::controls::ToQuaternionFromRotationVector(rvec_eigen));
226 Eigen::Translation3d translation(tvec_eigen);
227
228 const Eigen::Affine3d board_to_camera = translation * rotation;
229
James Kuszmaul7e958812023-02-11 15:34:31 -0800230 Eigen::Vector3d result = calibration_.CameraIntrinsicsEigen() *
231 camera_projection * board_to_camera *
232 Eigen::Vector3d::Zero();
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800233
234 // Found that drawAxis hangs if you try to draw with z values too
235 // small (trying to draw axes at inifinity)
Jim Ostrowski814d2812022-12-11 23:17:14 -0800236 // TODO<Jim>: Either track this down or reimplement drawAxes
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800237 if (result.z() < 0.01) {
238 LOG(INFO) << "Skipping, due to z value too small: " << result.z();
Jim Ostrowski814d2812022-12-11 23:17:14 -0800239 } else if (FLAGS_draw_axes == true) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800240 result /= result.z();
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800241 if (target_type_ == TargetType::kCharuco) {
James Kuszmaul7e958812023-02-11 15:34:31 -0800242 cv::aruco::drawAxis(rgb_image, calibration_.CameraIntrinsics(),
Jim Ostrowski814d2812022-12-11 23:17:14 -0800243 calibration_.CameraDistCoeffs(), rvecs[i], tvecs[i],
244 0.1);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800245 } else {
James Kuszmaul7e958812023-02-11 15:34:31 -0800246 cv::drawFrameAxes(rgb_image, calibration_.CameraIntrinsics(),
247 calibration_.CameraDistCoeffs(), rvecs[i], tvecs[i],
248 0.1);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800249 }
250 }
251 std::stringstream ss;
252 ss << "tvec[" << i << "] = " << tvecs[i];
253 y_coord += 25;
254 cv::putText(rgb_image, ss.str(), cv::Point(x_coord, y_coord),
255 cv::FONT_HERSHEY_PLAIN, 1.0, cv::Scalar(255, 255, 255));
256 ss.str("");
257 ss << "rvec[" << i << "] = " << rvecs[i];
258 y_coord += 25;
259 cv::putText(rgb_image, ss.str(), cv::Point(x_coord, y_coord),
260 cv::FONT_HERSHEY_PLAIN, 1.0, cv::Scalar(255, 255, 255));
261 }
262}
263
264void CharucoExtractor::PackPoseResults(
265 std::vector<cv::Vec3d> &rvecs, std::vector<cv::Vec3d> &tvecs,
266 std::vector<Eigen::Vector3d> *rvecs_eigen,
267 std::vector<Eigen::Vector3d> *tvecs_eigen) {
268 for (cv::Vec3d rvec : rvecs) {
269 Eigen::Vector3d rvec_eigen = Eigen::Vector3d::Zero();
270 cv::cv2eigen(rvec, rvec_eigen);
271 rvecs_eigen->emplace_back(rvec_eigen);
272 }
273
274 for (cv::Vec3d tvec : tvecs) {
275 Eigen::Vector3d tvec_eigen = Eigen::Vector3d::Zero();
276 cv::cv2eigen(tvec, tvec_eigen);
277 tvecs_eigen->emplace_back(tvec_eigen);
278 }
279}
280
Austin Schuh25837f22021-06-27 15:49:14 -0700281CharucoExtractor::CharucoExtractor(
James Kuszmaul7e958812023-02-11 15:34:31 -0800282 aos::EventLoop *event_loop,
283 const calibration::CameraCalibration *calibration, TargetType target_type,
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800284 std::string_view image_channel,
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800285 std::function<void(cv::Mat, monotonic_clock::time_point,
286 std::vector<cv::Vec4i>,
287 std::vector<std::vector<cv::Point2f>>, bool,
288 std::vector<Eigen::Vector3d>,
289 std::vector<Eigen::Vector3d>)> &&handle_charuco_fn)
Austin Schuhea7b0142021-10-08 22:04:53 -0700290 : event_loop_(event_loop),
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800291 target_type_(target_type),
292 image_channel_(image_channel),
James Kuszmaul7e958812023-02-11 15:34:31 -0800293 calibration_(CHECK_NOTNULL(calibration)),
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800294 handle_charuco_(std::move(handle_charuco_fn)) {
295 SetupTargetData();
Austin Schuh25837f22021-06-27 15:49:14 -0700296
James Kuszmaul7e958812023-02-11 15:34:31 -0800297 LOG(INFO) << "Camera matrix " << calibration_.CameraIntrinsics();
298 LOG(INFO) << "Distortion Coefficients " << calibration_.CameraDistCoeffs();
Austin Schuh25837f22021-06-27 15:49:14 -0700299
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800300 LOG(INFO) << "Connecting to channel " << image_channel_;
Austin Schuh25837f22021-06-27 15:49:14 -0700301}
302
Austin Schuhea7b0142021-10-08 22:04:53 -0700303void CharucoExtractor::HandleImage(cv::Mat rgb_image,
304 const monotonic_clock::time_point eof) {
305 const double age_double =
306 std::chrono::duration_cast<std::chrono::duration<double>>(
307 event_loop_->monotonic_now() - eof)
308 .count();
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800309
Jim Ostrowski814d2812022-12-11 23:17:14 -0800310 // Have found this useful if there is blurry / noisy images
311 if (FLAGS_gray_threshold > 0) {
312 cv::Mat gray;
313 cv::cvtColor(rgb_image, gray, cv::COLOR_BGR2GRAY);
314
315 cv::Mat thresh;
316 cv::threshold(gray, thresh, FLAGS_gray_threshold, 255, cv::THRESH_BINARY);
317 cv::cvtColor(thresh, rgb_image, cv::COLOR_GRAY2RGB);
318 }
319
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800320 // Set up the variables we'll use in the callback function
321 bool valid = false;
322 // Return a list of poses; for Charuco Board there will be just one
323 std::vector<Eigen::Vector3d> rvecs_eigen;
324 std::vector<Eigen::Vector3d> tvecs_eigen;
325
326 // ids and corners for initial aruco marker detections
Austin Schuh25837f22021-06-27 15:49:14 -0700327 std::vector<int> marker_ids;
328 std::vector<std::vector<cv::Point2f>> marker_corners;
329
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800330 // ids and corners for final, refined board / marker detections
331 // Using Vec4i type since it supports Charuco Diamonds
332 // And overloading it using 1st int in Vec4i for others target types
333 std::vector<cv::Vec4i> result_ids;
334 std::vector<std::vector<cv::Point2f>> result_corners;
Austin Schuh25837f22021-06-27 15:49:14 -0700335
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800336 // Do initial marker detection; this is the same for all target types
337 cv::aruco::detectMarkers(rgb_image, dictionary_, marker_corners, marker_ids);
338 cv::aruco::drawDetectedMarkers(rgb_image, marker_corners, marker_ids);
Austin Schuhea7b0142021-10-08 22:04:53 -0700339
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800340 VLOG(2) << "Handle Image, with target type = "
341 << static_cast<uint8_t>(target_type_) << " and " << marker_ids.size()
342 << " markers detected initially";
Austin Schuh25837f22021-06-27 15:49:14 -0700343
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800344 if (marker_ids.size() == 0) {
345 VLOG(2) << "Didn't find any markers";
346 } else {
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800347 if (target_type_ == TargetType::kCharuco) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800348 std::vector<int> charuco_ids;
349 std::vector<cv::Point2f> charuco_corners;
Austin Schuh25837f22021-06-27 15:49:14 -0700350
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800351 // If enough aruco markers detected for the Charuco board
352 if (marker_ids.size() >= FLAGS_min_charucos) {
353 // Run everything twice, once with the calibration, and once
354 // without. This lets us both collect data to calibrate the
355 // intrinsics of the camera (to determine the intrinsics from
356 // multiple samples), and also to use data from a previous/stored
357 // calibration to determine a more accurate pose in real time (used
358 // for extrinsics calibration)
359 cv::aruco::interpolateCornersCharuco(marker_corners, marker_ids,
360 rgb_image, board_, charuco_corners,
361 charuco_ids);
Austin Schuh25837f22021-06-27 15:49:14 -0700362
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800363 std::vector<cv::Point2f> charuco_corners_with_calibration;
364 std::vector<int> charuco_ids_with_calibration;
Austin Schuh25837f22021-06-27 15:49:14 -0700365
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800366 // This call uses a previous intrinsic calibration to get more
367 // accurate marker locations, for a better pose estimate
368 cv::aruco::interpolateCornersCharuco(
369 marker_corners, marker_ids, rgb_image, board_,
370 charuco_corners_with_calibration, charuco_ids_with_calibration,
James Kuszmaul7e958812023-02-11 15:34:31 -0800371 calibration_.CameraIntrinsics(), calibration_.CameraDistCoeffs());
Austin Schuh25837f22021-06-27 15:49:14 -0700372
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800373 if (charuco_ids.size() >= FLAGS_min_charucos) {
374 cv::aruco::drawDetectedCornersCharuco(
375 rgb_image, charuco_corners, charuco_ids, cv::Scalar(255, 0, 0));
Austin Schuh25837f22021-06-27 15:49:14 -0700376
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800377 cv::Vec3d rvec, tvec;
378 valid = cv::aruco::estimatePoseCharucoBoard(
379 charuco_corners_with_calibration, charuco_ids_with_calibration,
James Kuszmaul7e958812023-02-11 15:34:31 -0800380 board_, calibration_.CameraIntrinsics(),
381 calibration_.CameraDistCoeffs(), rvec, tvec);
Austin Schuh25837f22021-06-27 15:49:14 -0700382
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800383 // if charuco pose is valid, return pose, with ids and corners
384 if (valid) {
385 std::vector<cv::Vec3d> rvecs, tvecs;
386 rvecs.emplace_back(rvec);
387 tvecs.emplace_back(tvec);
388 DrawTargetPoses(rgb_image, rvecs, tvecs);
Austin Schuh25837f22021-06-27 15:49:14 -0700389
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800390 PackPoseResults(rvecs, tvecs, &rvecs_eigen, &tvecs_eigen);
391 // Store the corners without calibration, since we use them to
392 // do calibration
393 result_corners.emplace_back(charuco_corners);
394 for (auto id : charuco_ids) {
395 result_ids.emplace_back(cv::Vec4i{id, 0, 0, 0});
396 }
397 } else {
398 VLOG(2) << "Age: " << age_double << ", invalid charuco board pose";
399 }
Jim Ostrowski634b2652022-03-04 02:10:53 -0800400 } else {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800401 VLOG(2) << "Age: " << age_double << ", not enough charuco IDs, got "
402 << charuco_ids.size() << ", needed " << FLAGS_min_charucos;
Jim Ostrowski634b2652022-03-04 02:10:53 -0800403 }
Austin Schuh25837f22021-06-27 15:49:14 -0700404 } else {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800405 VLOG(2) << "Age: " << age_double
406 << ", not enough marker IDs for charuco board, got "
407 << marker_ids.size() << ", needed " << FLAGS_min_charucos;
408 }
milind-u09fb1252023-01-28 19:21:41 -0800409 } else if (target_type_ == TargetType::kAruco) {
410 // estimate pose for arucos doesn't return valid, so marking true
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800411 valid = true;
412 std::vector<cv::Vec3d> rvecs, tvecs;
James Kuszmaul7e958812023-02-11 15:34:31 -0800413 cv::aruco::estimatePoseSingleMarkers(
414 marker_corners, square_length_, calibration_.CameraIntrinsics(),
415 calibration_.CameraDistCoeffs(), rvecs, tvecs);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800416 DrawTargetPoses(rgb_image, rvecs, tvecs);
417
418 PackPoseResults(rvecs, tvecs, &rvecs_eigen, &tvecs_eigen);
419 for (uint i = 0; i < marker_ids.size(); i++) {
420 result_ids.emplace_back(cv::Vec4i{marker_ids[i], 0, 0, 0});
421 }
422 result_corners = marker_corners;
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800423 } else if (target_type_ == TargetType::kCharucoDiamond) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800424 // Extract the diamonds associated with the markers
425 std::vector<cv::Vec4i> diamond_ids;
426 std::vector<std::vector<cv::Point2f>> diamond_corners;
427 cv::aruco::detectCharucoDiamond(rgb_image, marker_corners, marker_ids,
428 square_length_ / marker_length_,
429 diamond_corners, diamond_ids);
430
Jim Ostrowskic7d90102023-03-09 14:47:25 -0800431 // Check that we have exactly one charuco diamond. For calibration, we
432 // can constrain things so that this is the case
433 if (diamond_ids.size() == 1) {
434 // TODO<Jim>: Could probably make this check more general than requiring
435 // range of ids
436 bool all_valid_ids = true;
437 for (uint i = 0; i < 4; i++) {
438 uint id = diamond_ids[0][i];
439 if ((id < FLAGS_min_id) || (id > FLAGS_max_id)) {
440 all_valid_ids = false;
441 LOG(INFO) << "Got invalid charuco id: " << id;
442 }
443 }
444 if (all_valid_ids) {
445 cv::aruco::drawDetectedDiamonds(rgb_image, diamond_corners,
446 diamond_ids);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800447
Jim Ostrowskic7d90102023-03-09 14:47:25 -0800448 // estimate pose for diamonds doesn't return valid, so marking true
449 valid = true;
450 std::vector<cv::Vec3d> rvecs, tvecs;
451 cv::aruco::estimatePoseSingleMarkers(
452 diamond_corners, square_length_, calibration_.CameraIntrinsics(),
453 calibration_.CameraDistCoeffs(), rvecs, tvecs);
454 DrawTargetPoses(rgb_image, rvecs, tvecs);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800455
Jim Ostrowskic7d90102023-03-09 14:47:25 -0800456 PackPoseResults(rvecs, tvecs, &rvecs_eigen, &tvecs_eigen);
457 result_ids = diamond_ids;
458 result_corners = diamond_corners;
459 } else {
460 LOG(INFO) << "Not all charuco ids were valid, so skipping";
461 }
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800462 } else {
Jim Ostrowskic7d90102023-03-09 14:47:25 -0800463 if (diamond_ids.size() == 0) {
464 // OK to not see any markers sometimes
465 VLOG(2)
466 << "Found aruco markers, but no valid charuco diamond targets";
467 } else {
468 // But should never detect multiple
469 LOG(FATAL) << "Found multiple charuco diamond markers. Should only "
470 "be one";
471 }
Austin Schuh25837f22021-06-27 15:49:14 -0700472 }
473 } else {
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800474 LOG(FATAL) << "Unknown target type: "
475 << static_cast<uint8_t>(target_type_);
Austin Schuh25837f22021-06-27 15:49:14 -0700476 }
Austin Schuh25837f22021-06-27 15:49:14 -0700477 }
Austin Schuhea7b0142021-10-08 22:04:53 -0700478
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800479 handle_charuco_(rgb_image, eof, result_ids, result_corners, valid,
480 rvecs_eigen, tvecs_eigen);
Austin Schuh25837f22021-06-27 15:49:14 -0700481}
482
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800483flatbuffers::Offset<foxglove::ImageAnnotations> BuildAnnotations(
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800484 flatbuffers::FlatBufferBuilder *fbb,
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800485 const aos::monotonic_clock::time_point monotonic_now,
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800486 const std::vector<std::vector<cv::Point2f>> &corners,
487 const std::vector<double> rgba_color, const double thickness,
488 const foxglove::PointsAnnotationType line_type) {
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800489 std::vector<flatbuffers::Offset<foxglove::PointsAnnotation>> rectangles;
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800490 for (const std::vector<cv::Point2f> &rectangle : corners) {
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800491 rectangles.push_back(BuildPointsAnnotation(
492 fbb, monotonic_now, rectangle, rgba_color, thickness, line_type));
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800493 }
494
495 const auto rectangles_offset = fbb->CreateVector(rectangles);
496 foxglove::ImageAnnotations::Builder annotation_builder(*fbb);
497 annotation_builder.add_points(rectangles_offset);
498 return annotation_builder.Finish();
499}
500
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800501flatbuffers::Offset<foxglove::PointsAnnotation> BuildPointsAnnotation(
502 flatbuffers::FlatBufferBuilder *fbb,
503 const aos::monotonic_clock::time_point monotonic_now,
504 const std::vector<cv::Point2f> &corners,
505 const std::vector<double> rgba_color, const double thickness,
506 const foxglove::PointsAnnotationType line_type) {
507 const struct timespec now_t = aos::time::to_timespec(monotonic_now);
508 foxglove::Time time{static_cast<uint32_t>(now_t.tv_sec),
509 static_cast<uint32_t>(now_t.tv_nsec)};
510 const flatbuffers::Offset<foxglove::Color> color_offset =
511 foxglove::CreateColor(*fbb, rgba_color[0], rgba_color[1], rgba_color[2],
512 rgba_color[3]);
513 std::vector<flatbuffers::Offset<foxglove::Point2>> points_offsets;
514 for (const cv::Point2f &point : corners) {
515 points_offsets.push_back(foxglove::CreatePoint2(*fbb, point.x, point.y));
516 }
517 const flatbuffers::Offset<
518 flatbuffers::Vector<flatbuffers::Offset<foxglove::Point2>>>
519 points_offset = fbb->CreateVector(points_offsets);
520 std::vector<flatbuffers::Offset<foxglove::Color>> color_offsets(
521 points_offsets.size(), color_offset);
522 auto colors_offset = fbb->CreateVector(color_offsets);
523 foxglove::PointsAnnotation::Builder points_builder(*fbb);
524 points_builder.add_timestamp(&time);
525 points_builder.add_type(line_type);
526 points_builder.add_points(points_offset);
527 points_builder.add_outline_color(color_offset);
528 points_builder.add_outline_colors(colors_offset);
529 points_builder.add_thickness(thickness);
530
531 return points_builder.Finish();
532}
533
James Kuszmauld6199be2023-02-11 19:56:28 -0800534TargetType TargetTypeFromString(std::string_view str) {
535 if (str == "aruco") {
536 return TargetType::kAruco;
537 } else if (str == "charuco") {
538 return TargetType::kCharuco;
539 } else if (str == "charuco_diamond") {
540 return TargetType::kCharucoDiamond;
541 } else {
542 LOG(FATAL) << "Unknown target type: " << str
543 << ", expected: aruco|charuco|charuco_diamond";
544 }
545}
546
547std::ostream &operator<<(std::ostream &os, TargetType target_type) {
548 switch (target_type) {
549 case TargetType::kAruco:
550 os << "aruco";
551 break;
552 case TargetType::kCharuco:
553 os << "charuco";
554 break;
555 case TargetType::kCharucoDiamond:
556 os << "charuco_diamond";
557 break;
558 }
559 return os;
560}
561
Austin Schuh25837f22021-06-27 15:49:14 -0700562} // namespace vision
563} // namespace frc971