blob: 864c5e7ad1721be0e94f65d0f520078c7a215990 [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"
16#include "y2020/vision/sift/sift_generated.h"
17#include "y2020/vision/sift/sift_training_generated.h"
18#include "y2020/vision/tools/python_code/sift_training_data.h"
Austin Schuh25837f22021-06-27 15:49:14 -070019
Austin Schuh25837f22021-06-27 15:49:14 -070020DEFINE_string(board_template_path, "",
21 "If specified, write an image to the specified path for the "
22 "charuco board pattern.");
Jim Ostrowskib3cab972022-12-03 15:47:00 -080023DEFINE_bool(coarse_pattern, true, "If true, use coarse arucos; else, use fine");
24DEFINE_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 Ostrowskib3cab972022-12-03 15:47:00 -080028DEFINE_bool(visualize, false, "Whether to visualize the resulting data.");
Austin Schuh25837f22021-06-27 15:49:14 -070029
Milind Upadhyayc5beba12022-12-17 17:41:20 -080030DEFINE_uint32(age, 100, "Age to start dropping frames at.");
Austin Schuhc3419862023-01-08 13:54:36 -080031DEFINE_uint32(disable_delay, 100, "Time after an issue to disable tracing at.");
32
33DECLARE_bool(enable_ftrace);
34
Austin Schuh25837f22021-06-27 15:49:14 -070035namespace frc971 {
36namespace vision {
37namespace chrono = std::chrono;
Austin Schuhea7b0142021-10-08 22:04:53 -070038using aos::monotonic_clock;
Austin Schuh25837f22021-06-27 15:49:14 -070039
40CameraCalibration::CameraCalibration(
41 const absl::Span<const uint8_t> training_data_bfbs, std::string_view pi) {
42 const aos::FlatbufferSpan<sift::TrainingData> training_data(
43 training_data_bfbs);
44 CHECK(training_data.Verify());
45 camera_calibration_ = FindCameraCalibration(&training_data.message(), pi);
46}
47
48cv::Mat CameraCalibration::CameraIntrinsics() const {
49 const cv::Mat result(3, 3, CV_32F,
50 const_cast<void *>(static_cast<const void *>(
51 camera_calibration_->intrinsics()->data())));
52 CHECK_EQ(result.total(), camera_calibration_->intrinsics()->size());
53 return result;
54}
55
56Eigen::Matrix3d CameraCalibration::CameraIntrinsicsEigen() const {
57 cv::Mat camera_intrinsics = CameraIntrinsics();
58 Eigen::Matrix3d result;
59 cv::cv2eigen(camera_intrinsics, result);
60 return result;
61}
62
63cv::Mat CameraCalibration::CameraDistCoeffs() const {
64 const cv::Mat result(5, 1, CV_32F,
65 const_cast<void *>(static_cast<const void *>(
66 camera_calibration_->dist_coeffs()->data())));
67 CHECK_EQ(result.total(), camera_calibration_->dist_coeffs()->size());
68 return result;
69}
70
71const sift::CameraCalibration *CameraCalibration::FindCameraCalibration(
72 const sift::TrainingData *const training_data, std::string_view pi) const {
73 std::optional<uint16_t> pi_number = aos::network::ParsePiNumber(pi);
74 std::optional<uint16_t> team_number =
75 aos::network::team_number_internal::ParsePiTeamNumber(pi);
76 CHECK(pi_number);
77 CHECK(team_number);
78 const std::string node_name = absl::StrFormat("pi%d", pi_number.value());
79 LOG(INFO) << "Looking for node name " << node_name << " team number "
80 << team_number.value();
81 for (const sift::CameraCalibration *candidate :
82 *training_data->camera_calibrations()) {
83 if (candidate->node_name()->string_view() != node_name) {
84 continue;
85 }
86 if (candidate->team_number() != team_number.value()) {
87 continue;
88 }
89 return candidate;
90 }
91 LOG(FATAL) << ": Failed to find camera calibration for " << node_name
92 << " on " << team_number.value();
93}
94
Austin Schuhea7b0142021-10-08 22:04:53 -070095ImageCallback::ImageCallback(
96 aos::EventLoop *event_loop, std::string_view channel,
Jim Ostrowskib3cab972022-12-03 15:47:00 -080097 std::function<void(cv::Mat, monotonic_clock::time_point)> &&handle_image_fn)
98
Austin Schuhea7b0142021-10-08 22:04:53 -070099 : event_loop_(event_loop),
100 server_fetcher_(
101 event_loop_->MakeFetcher<aos::message_bridge::ServerStatistics>(
102 "/aos")),
103 source_node_(aos::configuration::GetNode(
104 event_loop_->configuration(),
105 event_loop_->GetChannel<CameraImage>(channel)
106 ->source_node()
107 ->string_view())),
Austin Schuhc3419862023-01-08 13:54:36 -0800108 handle_image_(std::move(handle_image_fn)),
109 timer_fn_(event_loop->AddTimer([this]() { DisableTracing(); })) {
Austin Schuh25837f22021-06-27 15:49:14 -0700110 event_loop_->MakeWatcher(channel, [this](const CameraImage &image) {
Austin Schuhea7b0142021-10-08 22:04:53 -0700111 const monotonic_clock::time_point eof_source_node =
112 monotonic_clock::time_point(
113 chrono::nanoseconds(image.monotonic_timestamp_ns()));
Austin Schuhea7b0142021-10-08 22:04:53 -0700114 chrono::nanoseconds offset{0};
115 if (source_node_ != event_loop_->node()) {
Austin Schuhee8bc1e2021-11-20 16:23:41 -0800116 server_fetcher_.Fetch();
117 if (!server_fetcher_.get()) {
118 return;
119 }
120
Austin Schuhea7b0142021-10-08 22:04:53 -0700121 // If we are viewing this image from another node, convert to our
122 // monotonic clock.
123 const aos::message_bridge::ServerConnection *server_connection = nullptr;
124
125 for (const aos::message_bridge::ServerConnection *connection :
126 *server_fetcher_->connections()) {
127 CHECK(connection->has_node());
128 if (connection->node()->name()->string_view() ==
129 source_node_->name()->string_view()) {
130 server_connection = connection;
131 break;
132 }
133 }
134
135 CHECK(server_connection != nullptr) << ": Failed to find client";
136 if (!server_connection->has_monotonic_offset()) {
137 VLOG(1) << "No offset yet.";
138 return;
139 }
140 offset = chrono::nanoseconds(server_connection->monotonic_offset());
141 }
142
143 const monotonic_clock::time_point eof = eof_source_node - offset;
144
Jim Ostrowski977850f2022-01-22 21:04:22 -0800145 const monotonic_clock::duration age = event_loop_->monotonic_now() - eof;
Austin Schuh25837f22021-06-27 15:49:14 -0700146 const double age_double =
147 std::chrono::duration_cast<std::chrono::duration<double>>(age).count();
Austin Schuhc3419862023-01-08 13:54:36 -0800148 if (age > std::chrono::milliseconds(FLAGS_age)) {
149 if (FLAGS_enable_ftrace) {
150 ftrace_.FormatMessage("Too late receiving image, age: %f\n",
151 age_double);
152 if (FLAGS_disable_delay > 0) {
153 if (!disabling_) {
154 timer_fn_->Setup(event_loop_->monotonic_now() +
155 chrono::milliseconds(FLAGS_disable_delay));
156 disabling_ = true;
157 }
158 } else {
159 DisableTracing();
160 }
161 }
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800162 VLOG(2) << "Age: " << age_double << ", getting behind, skipping";
Austin Schuh25837f22021-06-27 15:49:14 -0700163 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());
Austin Schuhac402e92023-01-08 13:56:20 -0800169 switch (format_) {
170 case Format::GRAYSCALE: {
171 ftrace_.FormatMessage("Starting yuyv->greyscale\n");
172 cv::Mat gray_image(image_size, CV_8UC3);
173 cv::cvtColor(image_color_mat, gray_image, cv::COLOR_YUV2GRAY_YUYV);
174 handle_image_(gray_image, eof);
175 } break;
176 case Format::BGR: {
177 cv::Mat rgb_image(image_size, CV_8UC3);
178 cv::cvtColor(image_color_mat, rgb_image, cv::COLOR_YUV2BGR_YUYV);
179 handle_image_(rgb_image, eof);
180 } break;
181 case Format::YUYV2: {
182 handle_image_(image_color_mat, eof);
183 };
184 }
Austin Schuh25837f22021-06-27 15:49:14 -0700185 });
186}
187
Austin Schuhc3419862023-01-08 13:54:36 -0800188void ImageCallback::DisableTracing() {
189 disabling_ = false;
190 ftrace_.TurnOffOrDie();
191}
192
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800193void CharucoExtractor::SetupTargetData() {
194 // TODO(Jim): Put correct values here
195 marker_length_ = 0.15;
196 square_length_ = 0.1651;
197
198 // Only charuco board has a board associated with it
199 board_ = static_cast<cv::Ptr<cv::aruco::CharucoBoard>>(NULL);
200
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800201 if (target_type_ == TargetType::kCharuco ||
202 target_type_ == TargetType::kAruco) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800203 dictionary_ = cv::aruco::getPredefinedDictionary(
204 FLAGS_large_board ? cv::aruco::DICT_5X5_250 : cv::aruco::DICT_6X6_250);
205
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800206 if (target_type_ == TargetType::kCharuco) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800207 LOG(INFO) << "Using " << (FLAGS_large_board ? " large " : " small ")
208 << " charuco board with "
209 << (FLAGS_coarse_pattern ? "coarse" : "fine") << " pattern";
210 board_ =
211 (FLAGS_large_board
212 ? (FLAGS_coarse_pattern ? cv::aruco::CharucoBoard::create(
213 12, 9, 0.06, 0.04666, dictionary_)
214 : cv::aruco::CharucoBoard::create(
215 25, 18, 0.03, 0.0233, dictionary_))
216 : (FLAGS_coarse_pattern ? cv::aruco::CharucoBoard::create(
217 7, 5, 0.04, 0.025, dictionary_)
218 // TODO(jim): Need to figure out what
219 // size is for small board, fine pattern
220 : cv::aruco::CharucoBoard::create(
221 7, 5, 0.03, 0.0233, dictionary_)));
222 if (!FLAGS_board_template_path.empty()) {
223 cv::Mat board_image;
224 board_->draw(cv::Size(600, 500), board_image, 10, 1);
225 cv::imwrite(FLAGS_board_template_path, board_image);
226 }
227 }
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800228 } else if (target_type_ == TargetType::kCharucoDiamond) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800229 // TODO<Jim>: Measure this
230 marker_length_ = 0.15;
231 square_length_ = 0.1651;
232 dictionary_ = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_4X4_250);
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800233 } else if (target_type_ == TargetType::kAprilTag) {
Yash Chainanib31b0b12022-12-03 17:27:09 -0800234 // Tag will be 6 in (15.24 cm) according to
235 // https://www.firstinspires.org/robotics/frc/blog/2022-2023-approved-devices-rules-preview-and-vision-target-update
236 square_length_ = 0.1524;
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800237 dictionary_ =
Yash Chainanib31b0b12022-12-03 17:27:09 -0800238 cv::aruco::getPredefinedDictionary(cv::aruco::DICT_APRILTAG_16h5);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800239 } else {
240 // Bail out if it's not a supported target
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800241 LOG(FATAL) << "Target type undefined: "
242 << static_cast<uint8_t>(target_type_);
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800243 }
244}
245
246void CharucoExtractor::DrawTargetPoses(cv::Mat rgb_image,
247 std::vector<cv::Vec3d> rvecs,
248 std::vector<cv::Vec3d> tvecs) {
249 const Eigen::Matrix<double, 3, 4> camera_projection =
250 Eigen::Matrix<double, 3, 4>::Identity();
251
252 int x_coord = 10;
253 int y_coord = 0;
254 // draw axis for each marker
255 for (uint i = 0; i < rvecs.size(); i++) {
256 Eigen::Vector3d rvec_eigen, tvec_eigen;
257 cv::cv2eigen(rvecs[i], rvec_eigen);
258 cv::cv2eigen(tvecs[i], tvec_eigen);
259
260 Eigen::Quaternion<double> rotation(
261 frc971::controls::ToQuaternionFromRotationVector(rvec_eigen));
262 Eigen::Translation3d translation(tvec_eigen);
263
264 const Eigen::Affine3d board_to_camera = translation * rotation;
265
266 Eigen::Vector3d result = eigen_camera_matrix_ * camera_projection *
267 board_to_camera * Eigen::Vector3d::Zero();
268
269 // Found that drawAxis hangs if you try to draw with z values too
270 // small (trying to draw axes at inifinity)
271 // TODO<Jim>: Explore what real thresholds for this should be;
272 // likely Don't need to get rid of negative values
273 if (result.z() < 0.01) {
274 LOG(INFO) << "Skipping, due to z value too small: " << result.z();
275 } else {
276 result /= result.z();
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800277 if (target_type_ == TargetType::kCharuco) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800278 cv::aruco::drawAxis(rgb_image, camera_matrix_, dist_coeffs_, rvecs[i],
279 tvecs[i], 0.1);
280 } else {
281 cv::drawFrameAxes(rgb_image, camera_matrix_, dist_coeffs_, rvecs[i],
282 tvecs[i], 0.1);
283 }
284 }
285 std::stringstream ss;
286 ss << "tvec[" << i << "] = " << tvecs[i];
287 y_coord += 25;
288 cv::putText(rgb_image, ss.str(), cv::Point(x_coord, y_coord),
289 cv::FONT_HERSHEY_PLAIN, 1.0, cv::Scalar(255, 255, 255));
290 ss.str("");
291 ss << "rvec[" << i << "] = " << rvecs[i];
292 y_coord += 25;
293 cv::putText(rgb_image, ss.str(), cv::Point(x_coord, y_coord),
294 cv::FONT_HERSHEY_PLAIN, 1.0, cv::Scalar(255, 255, 255));
295 }
296}
297
298void CharucoExtractor::PackPoseResults(
299 std::vector<cv::Vec3d> &rvecs, std::vector<cv::Vec3d> &tvecs,
300 std::vector<Eigen::Vector3d> *rvecs_eigen,
301 std::vector<Eigen::Vector3d> *tvecs_eigen) {
302 for (cv::Vec3d rvec : rvecs) {
303 Eigen::Vector3d rvec_eigen = Eigen::Vector3d::Zero();
304 cv::cv2eigen(rvec, rvec_eigen);
305 rvecs_eigen->emplace_back(rvec_eigen);
306 }
307
308 for (cv::Vec3d tvec : tvecs) {
309 Eigen::Vector3d tvec_eigen = Eigen::Vector3d::Zero();
310 cv::cv2eigen(tvec, tvec_eigen);
311 tvecs_eigen->emplace_back(tvec_eigen);
312 }
313}
314
Austin Schuh25837f22021-06-27 15:49:14 -0700315CharucoExtractor::CharucoExtractor(
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800316 aos::EventLoop *event_loop, std::string_view pi, TargetType target_type,
317 std::string_view image_channel,
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800318 std::function<void(cv::Mat, monotonic_clock::time_point,
319 std::vector<cv::Vec4i>,
320 std::vector<std::vector<cv::Point2f>>, bool,
321 std::vector<Eigen::Vector3d>,
322 std::vector<Eigen::Vector3d>)> &&handle_charuco_fn)
Austin Schuhea7b0142021-10-08 22:04:53 -0700323 : event_loop_(event_loop),
324 calibration_(SiftTrainingData(), pi),
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800325 target_type_(target_type),
326 image_channel_(image_channel),
Austin Schuh25837f22021-06-27 15:49:14 -0700327 camera_matrix_(calibration_.CameraIntrinsics()),
328 eigen_camera_matrix_(calibration_.CameraIntrinsicsEigen()),
329 dist_coeffs_(calibration_.CameraDistCoeffs()),
330 pi_number_(aos::network::ParsePiNumber(pi)),
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800331 handle_charuco_(std::move(handle_charuco_fn)) {
332 SetupTargetData();
Austin Schuh25837f22021-06-27 15:49:14 -0700333
334 LOG(INFO) << "Camera matrix " << camera_matrix_;
335 LOG(INFO) << "Distortion Coefficients " << dist_coeffs_;
336
337 CHECK(pi_number_) << ": Invalid pi number " << pi
338 << ", failed to parse pi number";
339
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800340 LOG(INFO) << "Connecting to channel " << image_channel_;
Austin Schuh25837f22021-06-27 15:49:14 -0700341}
342
Austin Schuhea7b0142021-10-08 22:04:53 -0700343void CharucoExtractor::HandleImage(cv::Mat rgb_image,
344 const monotonic_clock::time_point eof) {
345 const double age_double =
346 std::chrono::duration_cast<std::chrono::duration<double>>(
347 event_loop_->monotonic_now() - eof)
348 .count();
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800349
350 // Set up the variables we'll use in the callback function
351 bool valid = false;
352 // Return a list of poses; for Charuco Board there will be just one
353 std::vector<Eigen::Vector3d> rvecs_eigen;
354 std::vector<Eigen::Vector3d> tvecs_eigen;
355
356 // ids and corners for initial aruco marker detections
Austin Schuh25837f22021-06-27 15:49:14 -0700357 std::vector<int> marker_ids;
358 std::vector<std::vector<cv::Point2f>> marker_corners;
359
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800360 // ids and corners for final, refined board / marker detections
361 // Using Vec4i type since it supports Charuco Diamonds
362 // And overloading it using 1st int in Vec4i for others target types
363 std::vector<cv::Vec4i> result_ids;
364 std::vector<std::vector<cv::Point2f>> result_corners;
Austin Schuh25837f22021-06-27 15:49:14 -0700365
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800366 // Do initial marker detection; this is the same for all target types
367 cv::aruco::detectMarkers(rgb_image, dictionary_, marker_corners, marker_ids);
368 cv::aruco::drawDetectedMarkers(rgb_image, marker_corners, marker_ids);
Austin Schuhea7b0142021-10-08 22:04:53 -0700369
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800370 VLOG(2) << "Handle Image, with target type = "
371 << static_cast<uint8_t>(target_type_) << " and " << marker_ids.size()
372 << " markers detected initially";
Austin Schuh25837f22021-06-27 15:49:14 -0700373
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800374 if (marker_ids.size() == 0) {
375 VLOG(2) << "Didn't find any markers";
376 } else {
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800377 if (target_type_ == TargetType::kCharuco) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800378 std::vector<int> charuco_ids;
379 std::vector<cv::Point2f> charuco_corners;
Austin Schuh25837f22021-06-27 15:49:14 -0700380
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800381 // If enough aruco markers detected for the Charuco board
382 if (marker_ids.size() >= FLAGS_min_charucos) {
383 // Run everything twice, once with the calibration, and once
384 // without. This lets us both collect data to calibrate the
385 // intrinsics of the camera (to determine the intrinsics from
386 // multiple samples), and also to use data from a previous/stored
387 // calibration to determine a more accurate pose in real time (used
388 // for extrinsics calibration)
389 cv::aruco::interpolateCornersCharuco(marker_corners, marker_ids,
390 rgb_image, board_, charuco_corners,
391 charuco_ids);
Austin Schuh25837f22021-06-27 15:49:14 -0700392
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800393 std::vector<cv::Point2f> charuco_corners_with_calibration;
394 std::vector<int> charuco_ids_with_calibration;
Austin Schuh25837f22021-06-27 15:49:14 -0700395
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800396 // This call uses a previous intrinsic calibration to get more
397 // accurate marker locations, for a better pose estimate
398 cv::aruco::interpolateCornersCharuco(
399 marker_corners, marker_ids, rgb_image, board_,
400 charuco_corners_with_calibration, charuco_ids_with_calibration,
401 camera_matrix_, dist_coeffs_);
Austin Schuh25837f22021-06-27 15:49:14 -0700402
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800403 if (charuco_ids.size() >= FLAGS_min_charucos) {
404 cv::aruco::drawDetectedCornersCharuco(
405 rgb_image, charuco_corners, charuco_ids, cv::Scalar(255, 0, 0));
Austin Schuh25837f22021-06-27 15:49:14 -0700406
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800407 cv::Vec3d rvec, tvec;
408 valid = cv::aruco::estimatePoseCharucoBoard(
409 charuco_corners_with_calibration, charuco_ids_with_calibration,
410 board_, camera_matrix_, dist_coeffs_, rvec, tvec);
Austin Schuh25837f22021-06-27 15:49:14 -0700411
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800412 // if charuco pose is valid, return pose, with ids and corners
413 if (valid) {
414 std::vector<cv::Vec3d> rvecs, tvecs;
415 rvecs.emplace_back(rvec);
416 tvecs.emplace_back(tvec);
417 DrawTargetPoses(rgb_image, rvecs, tvecs);
Austin Schuh25837f22021-06-27 15:49:14 -0700418
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800419 PackPoseResults(rvecs, tvecs, &rvecs_eigen, &tvecs_eigen);
420 // Store the corners without calibration, since we use them to
421 // do calibration
422 result_corners.emplace_back(charuco_corners);
423 for (auto id : charuco_ids) {
424 result_ids.emplace_back(cv::Vec4i{id, 0, 0, 0});
425 }
426 } else {
427 VLOG(2) << "Age: " << age_double << ", invalid charuco board pose";
428 }
Jim Ostrowski634b2652022-03-04 02:10:53 -0800429 } else {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800430 VLOG(2) << "Age: " << age_double << ", not enough charuco IDs, got "
431 << charuco_ids.size() << ", needed " << FLAGS_min_charucos;
Jim Ostrowski634b2652022-03-04 02:10:53 -0800432 }
Austin Schuh25837f22021-06-27 15:49:14 -0700433 } else {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800434 VLOG(2) << "Age: " << age_double
435 << ", not enough marker IDs for charuco board, got "
436 << marker_ids.size() << ", needed " << FLAGS_min_charucos;
437 }
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800438 } else if (target_type_ == TargetType::kAprilTag ||
439 target_type_ == TargetType::kAruco) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800440 // estimate pose for april tags doesn't return valid, so marking true
441 valid = true;
442 std::vector<cv::Vec3d> rvecs, tvecs;
443 cv::aruco::estimatePoseSingleMarkers(marker_corners, square_length_,
444 camera_matrix_, dist_coeffs_, rvecs,
445 tvecs);
446 DrawTargetPoses(rgb_image, rvecs, tvecs);
447
448 PackPoseResults(rvecs, tvecs, &rvecs_eigen, &tvecs_eigen);
449 for (uint i = 0; i < marker_ids.size(); i++) {
450 result_ids.emplace_back(cv::Vec4i{marker_ids[i], 0, 0, 0});
451 }
452 result_corners = marker_corners;
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800453 } else if (target_type_ == TargetType::kCharucoDiamond) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800454 // Extract the diamonds associated with the markers
455 std::vector<cv::Vec4i> diamond_ids;
456 std::vector<std::vector<cv::Point2f>> diamond_corners;
457 cv::aruco::detectCharucoDiamond(rgb_image, marker_corners, marker_ids,
458 square_length_ / marker_length_,
459 diamond_corners, diamond_ids);
460
461 // Check to see if we found any diamond targets
462 if (diamond_ids.size() > 0) {
463 cv::aruco::drawDetectedDiamonds(rgb_image, diamond_corners,
464 diamond_ids);
465
466 // estimate pose for diamonds doesn't return valid, so marking true
467 valid = true;
468 std::vector<cv::Vec3d> rvecs, tvecs;
469 cv::aruco::estimatePoseSingleMarkers(diamond_corners, square_length_,
470 camera_matrix_, dist_coeffs_,
471 rvecs, tvecs);
472 DrawTargetPoses(rgb_image, rvecs, tvecs);
473
474 PackPoseResults(rvecs, tvecs, &rvecs_eigen, &tvecs_eigen);
475 result_ids = diamond_ids;
476 result_corners = diamond_corners;
477 } else {
478 VLOG(2) << "Found aruco markers, but no charuco diamond targets";
Austin Schuh25837f22021-06-27 15:49:14 -0700479 }
480 } else {
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800481 LOG(FATAL) << "Unknown target type: "
482 << static_cast<uint8_t>(target_type_);
Austin Schuh25837f22021-06-27 15:49:14 -0700483 }
Austin Schuh25837f22021-06-27 15:49:14 -0700484 }
Austin Schuhea7b0142021-10-08 22:04:53 -0700485
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800486 handle_charuco_(rgb_image, eof, result_ids, result_corners, valid,
487 rvecs_eigen, tvecs_eigen);
Austin Schuh25837f22021-06-27 15:49:14 -0700488}
489
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800490flatbuffers::Offset<foxglove::ImageAnnotations> BuildAnnotations(
491 const aos::monotonic_clock::time_point monotonic_now,
492 const std::vector<std::vector<cv::Point2f>> &corners,
493 flatbuffers::FlatBufferBuilder *fbb) {
494 std::vector<flatbuffers::Offset<foxglove::PointsAnnotation>> rectangles;
495 const struct timespec now_t = aos::time::to_timespec(monotonic_now);
496 foxglove::Time time{static_cast<uint32_t>(now_t.tv_sec),
497 static_cast<uint32_t>(now_t.tv_nsec)};
498 const flatbuffers::Offset<foxglove::Color> color_offset =
499 foxglove::CreateColor(*fbb, 0.0, 1.0, 0.0, 1.0);
500 for (const std::vector<cv::Point2f> &rectangle : corners) {
501 std::vector<flatbuffers::Offset<foxglove::Point2>> points_offsets;
502 for (const cv::Point2f &point : rectangle) {
503 points_offsets.push_back(foxglove::CreatePoint2(*fbb, point.x, point.y));
504 }
505 const flatbuffers::Offset<
506 flatbuffers::Vector<flatbuffers::Offset<foxglove::Point2>>>
507 points_offset = fbb->CreateVector(points_offsets);
508 std::vector<flatbuffers::Offset<foxglove::Color>> color_offsets(
509 points_offsets.size(), color_offset);
510 auto colors_offset = fbb->CreateVector(color_offsets);
511 foxglove::PointsAnnotation::Builder points_builder(*fbb);
512 points_builder.add_timestamp(&time);
513 points_builder.add_type(foxglove::PointsAnnotationType::POINTS);
514 points_builder.add_points(points_offset);
515 points_builder.add_outline_color(color_offset);
516 points_builder.add_outline_colors(colors_offset);
517 points_builder.add_thickness(2.0);
518 rectangles.push_back(points_builder.Finish());
519 }
520
521 const auto rectangles_offset = fbb->CreateVector(rectangles);
522 foxglove::ImageAnnotations::Builder annotation_builder(*fbb);
523 annotation_builder.add_points(rectangles_offset);
524 return annotation_builder.Finish();
525}
526
Austin Schuh25837f22021-06-27 15:49:14 -0700527} // namespace vision
528} // namespace frc971