blob: 0605eb2cd79cadf05991b33ecb41bbc176773b7b [file] [log] [blame]
Maxwell Hendersonfebee252023-01-28 16:53:52 -08001#include "y2023/vision/aprilrobotics.h"
2
Jim Ostrowski49be8232023-03-23 01:00:14 -07003#include <opencv2/highgui.hpp>
4
milind-ua30a4a12023-03-24 20:49:41 -07005#include "y2023/vision/vision_util.h"
6
Maxwell Hendersonfebee252023-01-28 16:53:52 -08007DEFINE_bool(
8 debug, false,
9 "If true, dump a ton of debug and crash on the first valid detection.");
10
Jim Ostrowskid03f9892023-03-25 11:57:54 -070011DEFINE_double(min_decision_margin, 50.0,
milind-uf2a4e322023-02-01 19:33:10 -080012 "Minimum decision margin (confidence) for an apriltag detection");
Jim Ostrowski14124a32023-03-03 22:16:07 -080013DEFINE_int32(pixel_border, 10,
Jim Ostrowski437b1fb2023-02-26 10:12:01 -080014 "Size of image border within which to reject detected corners");
milind-u60e7fe52023-02-26 16:13:50 -080015DEFINE_double(
milind-u8773c232023-03-11 14:59:06 -080016 max_expected_distortion, 0.314,
milind-u60e7fe52023-02-26 16:13:50 -080017 "Maximum expected value for unscaled distortion factors. Will scale "
18 "distortion factors so that this value (and a higher distortion) maps to "
19 "1.0.");
milind-ude9045f2023-03-25 18:17:12 -070020DEFINE_uint64(pose_estimation_iterations, 50,
21 "Number of iterations for apriltag pose estimation.");
milind-uf2a4e322023-02-01 19:33:10 -080022
Stephan Pleinesf63bde82024-01-13 15:59:33 -080023namespace y2023::vision {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080024
Austin Schuhd2667932023-02-04 16:22:39 -080025namespace chrono = std::chrono;
26
Maxwell Hendersonfebee252023-01-28 16:53:52 -080027AprilRoboticsDetector::AprilRoboticsDetector(aos::EventLoop *event_loop,
milind-ua30a4a12023-03-24 20:49:41 -070028 std::string_view channel_name,
29 bool flip_image)
James Kuszmauld67f6d22023-02-05 17:37:25 -080030 : calibration_data_(event_loop),
milind-uf5b3b4b2023-02-26 14:50:38 -080031 image_size_(0, 0),
milind-ua30a4a12023-03-24 20:49:41 -070032 flip_image_(flip_image),
33 node_name_(event_loop->node()->name()->string_view()),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080034 ftrace_(),
milind-ufbc5c812023-04-06 21:24:29 -070035 image_callback_(
36 event_loop, channel_name,
37 [&](cv::Mat image_color_mat,
38 const aos::monotonic_clock::time_point eof) {
39 HandleImage(image_color_mat, eof);
40 },
41 chrono::milliseconds(5)),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080042 target_map_sender_(
Yash Chainani728ae222023-02-04 19:48:12 -080043 event_loop->MakeSender<frc971::vision::TargetMap>("/camera")),
milind-u7aa29e22023-02-23 20:22:01 -080044 image_annotations_sender_(
milind-u99b1a762023-03-12 16:48:32 -070045 event_loop->MakeSender<foxglove::ImageAnnotations>("/camera")),
46 rejections_(0) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080047 tag_family_ = tag16h5_create();
48 tag_detector_ = apriltag_detector_create();
49
50 apriltag_detector_add_family_bits(tag_detector_, tag_family_, 1);
51 tag_detector_->nthreads = 6;
52 tag_detector_->wp = workerpool_create(tag_detector_->nthreads);
53 tag_detector_->qtp.min_white_black_diff = 5;
54 tag_detector_->debug = FLAGS_debug;
55
56 std::string hostname = aos::network::GetHostname();
57
58 // Check team string is valid
James Kuszmauld67f6d22023-02-05 17:37:25 -080059 calibration_ = FindCameraCalibration(
60 calibration_data_.constants(), event_loop->node()->name()->string_view());
milind-uf2a4e322023-02-01 19:33:10 -080061
62 extrinsics_ = CameraExtrinsics(calibration_);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080063 intrinsics_ = CameraIntrinsics(calibration_);
milind-uf2a4e322023-02-01 19:33:10 -080064 // Create an undistort projection matrix using the intrinsics
65 projection_matrix_ = cv::Mat::zeros(3, 4, CV_64F);
66 intrinsics_.rowRange(0, 3).colRange(0, 3).copyTo(
67 projection_matrix_.rowRange(0, 3).colRange(0, 3));
68
69 dist_coeffs_ = CameraDistCoeffs(calibration_);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080070
71 image_callback_.set_format(frc971::vision::ImageCallback::Format::GRAYSCALE);
72}
73
74AprilRoboticsDetector::~AprilRoboticsDetector() {
75 apriltag_detector_destroy(tag_detector_);
76 free(tag_family_);
77}
78
79void AprilRoboticsDetector::SetWorkerpoolAffinities() {
80 for (int i = 0; i < tag_detector_->wp->nthreads; i++) {
81 cpu_set_t affinity;
82 CPU_ZERO(&affinity);
83 CPU_SET(i, &affinity);
84 pthread_setaffinity_np(tag_detector_->wp->threads[i], sizeof(affinity),
85 &affinity);
86 struct sched_param param;
87 param.sched_priority = 20;
88 int res = pthread_setschedparam(tag_detector_->wp->threads[i], SCHED_FIFO,
89 &param);
90 PCHECK(res == 0) << "Failed to set priority of threadpool threads";
91 }
92}
93
milind-uf2a4e322023-02-01 19:33:10 -080094void AprilRoboticsDetector::HandleImage(cv::Mat image_grayscale,
milind-u09fb1252023-01-28 19:21:41 -080095 aos::monotonic_clock::time_point eof) {
milind-uf5b3b4b2023-02-26 14:50:38 -080096 image_size_ = image_grayscale.size();
97
milind-u99b1a762023-03-12 16:48:32 -070098 DetectionResult result = DetectTags(image_grayscale, eof);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080099
100 auto builder = target_map_sender_.MakeBuilder();
101 std::vector<flatbuffers::Offset<frc971::vision::TargetPoseFbs>> target_poses;
milind-ude9045f2023-03-25 18:17:12 -0700102 for (auto &detection : result.detections) {
103 auto *fbb = builder.fbb();
104 auto pose = BuildTargetPose(detection, fbb);
105 DestroyPose(&detection.pose);
106 target_poses.emplace_back(pose);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800107 }
108 const auto target_poses_offset = builder.fbb()->CreateVector(target_poses);
109 auto target_map_builder = builder.MakeBuilder<frc971::vision::TargetMap>();
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800110 target_map_builder.add_target_poses(target_poses_offset);
milind-u09fb1252023-01-28 19:21:41 -0800111 target_map_builder.add_monotonic_timestamp_ns(eof.time_since_epoch().count());
milind-u99b1a762023-03-12 16:48:32 -0700112 target_map_builder.add_rejections(result.rejections);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800113 builder.CheckOk(builder.Send(target_map_builder.Finish()));
114}
115
116flatbuffers::Offset<frc971::vision::TargetPoseFbs>
milind-ufc8ab702023-02-26 14:14:39 -0800117AprilRoboticsDetector::BuildTargetPose(const Detection &detection,
milind-u681c4712023-02-23 21:22:50 -0800118 flatbuffers::FlatBufferBuilder *fbb) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800119 const auto T =
milind-ufc8ab702023-02-26 14:14:39 -0800120 Eigen::Translation3d(detection.pose.t->data[0], detection.pose.t->data[1],
121 detection.pose.t->data[2]);
milind-u3f5f83c2023-01-29 15:23:51 -0800122 const auto position_offset =
123 frc971::vision::CreatePosition(*fbb, T.x(), T.y(), T.z());
124
milind-u633c4c02023-02-25 22:51:45 -0800125 // Aprilrobotics stores the rotation matrix in row-major order
126 const auto orientation = Eigen::Quaterniond(
milind-ufc8ab702023-02-26 14:14:39 -0800127 Eigen::Matrix<double, 3, 3, Eigen::RowMajor>(detection.pose.R->data));
milind-u3f5f83c2023-01-29 15:23:51 -0800128 const auto orientation_offset = frc971::vision::CreateQuaternion(
129 *fbb, orientation.w(), orientation.x(), orientation.y(), orientation.z());
130
milind-u681c4712023-02-23 21:22:50 -0800131 return frc971::vision::CreateTargetPoseFbs(
milind-ufc8ab702023-02-26 14:14:39 -0800132 *fbb, detection.det.id, position_offset, orientation_offset,
milind-uf5b3b4b2023-02-26 14:50:38 -0800133 detection.det.decision_margin, detection.pose_error,
milind-ude9045f2023-03-25 18:17:12 -0700134 detection.distortion_factor, detection.pose_error_ratio);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800135}
136
milind-uf2a4e322023-02-01 19:33:10 -0800137void AprilRoboticsDetector::UndistortDetection(
138 apriltag_detection_t *det) const {
139 // 4 corners
140 constexpr size_t kRows = 4;
141 // 2d points
142 constexpr size_t kCols = 2;
143
144 cv::Mat distorted_points(kRows, kCols, CV_64F, det->p);
145 cv::Mat undistorted_points = cv::Mat::zeros(kRows, kCols, CV_64F);
146
147 // Undistort the april tag points
148 cv::undistortPoints(distorted_points, undistorted_points, intrinsics_,
149 dist_coeffs_, cv::noArray(), projection_matrix_);
150
151 // Copy the undistorted points into det
152 for (size_t i = 0; i < kRows; i++) {
153 for (size_t j = 0; j < kCols; j++) {
154 det->p[i][j] = undistorted_points.at<double>(i, j);
155 }
156 }
157}
158
milind-uf5b3b4b2023-02-26 14:50:38 -0800159double AprilRoboticsDetector::ComputeDistortionFactor(
160 const std::vector<cv::Point2f> &orig_corners,
161 const std::vector<cv::Point2f> &corners) {
162 CHECK_EQ(orig_corners.size(), 4ul);
163 CHECK_EQ(corners.size(), 4ul);
164
165 double avg_distance = 0.0;
166 for (size_t i = 0; i < corners.size(); i++) {
167 avg_distance += cv::norm(orig_corners[i] - corners[i]);
168 }
169 avg_distance /= corners.size();
170
milind-u8773c232023-03-11 14:59:06 -0800171 // Normalize avg_distance by dividing by the image diagonal,
172 // and then the maximum expected distortion
milind-uf5b3b4b2023-02-26 14:50:38 -0800173 double distortion_factor =
174 avg_distance /
milind-u8773c232023-03-11 14:59:06 -0800175 cv::norm(cv::Point2d(image_size_.width, image_size_.height));
milind-u60e7fe52023-02-26 16:13:50 -0800176 return std::min(distortion_factor / FLAGS_max_expected_distortion, 1.0);
milind-uf5b3b4b2023-02-26 14:50:38 -0800177}
178
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800179std::vector<cv::Point2f> AprilRoboticsDetector::MakeCornerVector(
180 const apriltag_detection_t *det) {
181 std::vector<cv::Point2f> corner_points;
182 corner_points.emplace_back(det->p[0][0], det->p[0][1]);
183 corner_points.emplace_back(det->p[1][0], det->p[1][1]);
184 corner_points.emplace_back(det->p[2][0], det->p[2][1]);
185 corner_points.emplace_back(det->p[3][0], det->p[3][1]);
186
187 return corner_points;
188}
189
milind-ude9045f2023-03-25 18:17:12 -0700190void AprilRoboticsDetector::DestroyPose(apriltag_pose_t *pose) const {
191 matd_destroy(pose->R);
192 matd_destroy(pose->t);
193}
194
milind-u99b1a762023-03-12 16:48:32 -0700195AprilRoboticsDetector::DetectionResult AprilRoboticsDetector::DetectTags(
milind-ufc8ab702023-02-26 14:14:39 -0800196 cv::Mat image, aos::monotonic_clock::time_point eof) {
Jim Ostrowski49be8232023-03-23 01:00:14 -0700197 cv::Mat color_image;
198 cvtColor(image, color_image, cv::COLOR_GRAY2RGB);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800199 const aos::monotonic_clock::time_point start_time =
200 aos::monotonic_clock::now();
201
202 image_u8_t im = {
milind-u09fb1252023-01-28 19:21:41 -0800203 .width = image.cols,
204 .height = image.rows,
205 .stride = image.cols,
206 .buf = image.data,
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800207 };
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800208 const uint32_t min_x = FLAGS_pixel_border;
209 const uint32_t max_x = image.cols - FLAGS_pixel_border;
Jim Ostrowski0197d6b2023-03-04 12:41:13 -0800210 const uint32_t min_y = FLAGS_pixel_border;
211 const uint32_t max_y = image.rows - FLAGS_pixel_border;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800212
213 ftrace_.FormatMessage("Starting detect\n");
214 zarray_t *detections = apriltag_detector_detect(tag_detector_, &im);
215 ftrace_.FormatMessage("Done detecting\n");
216
milind-ufc8ab702023-02-26 14:14:39 -0800217 std::vector<Detection> results;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800218
milind-u7aa29e22023-02-23 20:22:01 -0800219 auto builder = image_annotations_sender_.MakeBuilder();
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800220 std::vector<flatbuffers::Offset<foxglove::PointsAnnotation>> foxglove_corners;
Yash Chainani728ae222023-02-04 19:48:12 -0800221
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800222 for (int i = 0; i < zarray_size(detections); i++) {
223 apriltag_detection_t *det;
224 zarray_get(detections, i, &det);
225
milind-uf2a4e322023-02-01 19:33:10 -0800226 if (det->decision_margin > FLAGS_min_decision_margin) {
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800227 if (det->p[0][0] < min_x || det->p[0][0] > max_x ||
228 det->p[1][0] < min_x || det->p[1][0] > max_x ||
229 det->p[2][0] < min_x || det->p[2][0] > max_x ||
Jim Ostrowski0197d6b2023-03-04 12:41:13 -0800230 det->p[3][0] < min_x || det->p[3][0] > max_x ||
231 det->p[0][1] < min_y || det->p[0][1] > max_y ||
232 det->p[1][1] < min_y || det->p[1][1] > max_y ||
233 det->p[2][1] < min_y || det->p[2][1] > max_y ||
234 det->p[3][1] < min_y || det->p[3][1] > max_y) {
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800235 VLOG(1) << "Rejecting detection because corner is outside pixel border";
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800236 // Send rejected corner points in red
237 std::vector<cv::Point2f> rejected_corner_points = MakeCornerVector(det);
238 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
239 builder.fbb(), eof, rejected_corner_points,
240 std::vector<double>{1.0, 0.0, 0.0, 0.5}));
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800241 continue;
242 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800243 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
244 << " margin: " << det->decision_margin;
245
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800246 // First create an apriltag_detection_info_t struct using your known
247 // parameters.
248 apriltag_detection_info_t info;
249 info.det = det;
250 info.tagsize = 0.1524;
milind-uf2a4e322023-02-01 19:33:10 -0800251
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800252 info.fx = intrinsics_.at<double>(0, 0);
253 info.fy = intrinsics_.at<double>(1, 1);
254 info.cx = intrinsics_.at<double>(0, 2);
255 info.cy = intrinsics_.at<double>(1, 2);
256
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800257 // Send original corner points in green
258 std::vector<cv::Point2f> orig_corner_points = MakeCornerVector(det);
259 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
260 builder.fbb(), eof, orig_corner_points,
261 std::vector<double>{0.0, 1.0, 0.0, 0.5}));
Jim Ostrowskid2b5c912023-02-26 00:59:35 -0800262
milind-ueccac3c2023-02-25 20:54:47 -0800263 UndistortDetection(det);
264
milind-uf5b3b4b2023-02-26 14:50:38 -0800265 const aos::monotonic_clock::time_point before_pose_estimation =
266 aos::monotonic_clock::now();
267
milind-ude9045f2023-03-25 18:17:12 -0700268 apriltag_pose_t pose_1;
269 apriltag_pose_t pose_2;
270 double pose_error_1;
271 double pose_error_2;
272 estimate_tag_pose_orthogonal_iteration(&info, &pose_error_1, &pose_1,
273 &pose_error_2, &pose_2,
274 FLAGS_pose_estimation_iterations);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800275
276 const aos::monotonic_clock::time_point after_pose_estimation =
277 aos::monotonic_clock::now();
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800278 VLOG(1) << "Took "
Austin Schuhd2667932023-02-04 16:22:39 -0800279 << chrono::duration<double>(after_pose_estimation -
280 before_pose_estimation)
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800281 .count()
282 << " seconds for pose estimation";
milind-ude9045f2023-03-25 18:17:12 -0700283 VLOG(1) << "Pose err 1: " << pose_error_1;
284 VLOG(1) << "Pose err 2: " << pose_error_2;
Yash Chainani728ae222023-02-04 19:48:12 -0800285
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800286 // Send undistorted corner points in pink
287 std::vector<cv::Point2f> corner_points = MakeCornerVector(det);
288 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
289 builder.fbb(), eof, corner_points,
290 std::vector<double>{1.0, 0.75, 0.8, 1.0}));
milind-uf5b3b4b2023-02-26 14:50:38 -0800291
292 double distortion_factor =
293 ComputeDistortionFactor(orig_corner_points, corner_points);
294
milind-ude9045f2023-03-25 18:17:12 -0700295 // We get two estimates for poses.
296 // Choose the one with the lower estimation error
297 bool use_pose_1 = (pose_error_1 < pose_error_2);
298 auto best_pose = (use_pose_1 ? pose_1 : pose_2);
299 auto secondary_pose = (use_pose_1 ? pose_2 : pose_1);
300 double best_pose_error = (use_pose_1 ? pose_error_1 : pose_error_2);
301 double secondary_pose_error = (use_pose_1 ? pose_error_2 : pose_error_1);
302
303 CHECK_NE(best_pose_error, std::numeric_limits<double>::infinity())
304 << "Got no valid pose estimations, this should not be possible.";
305 double pose_error_ratio = best_pose_error / secondary_pose_error;
306
307 // Destroy the secondary pose if we got one
308 if (secondary_pose_error != std::numeric_limits<double>::infinity()) {
309 DestroyPose(&secondary_pose);
310 }
311
milind-uf5b3b4b2023-02-26 14:50:38 -0800312 results.emplace_back(Detection{.det = *det,
milind-ude9045f2023-03-25 18:17:12 -0700313 .pose = best_pose,
314 .pose_error = best_pose_error,
315 .distortion_factor = distortion_factor,
316 .pose_error_ratio = pose_error_ratio});
317
Jim Ostrowski49be8232023-03-23 01:00:14 -0700318 if (FLAGS_visualize) {
319 // Draw raw (distorted) corner points in green
320 cv::line(color_image, orig_corner_points[0], orig_corner_points[1],
321 cv::Scalar(0, 255, 0), 2);
322 cv::line(color_image, orig_corner_points[1], orig_corner_points[2],
323 cv::Scalar(0, 255, 0), 2);
324 cv::line(color_image, orig_corner_points[2], orig_corner_points[3],
325 cv::Scalar(0, 255, 0), 2);
326 cv::line(color_image, orig_corner_points[3], orig_corner_points[0],
327 cv::Scalar(0, 255, 0), 2);
328
329 // Draw undistorted corner points in red
330 cv::line(color_image, corner_points[0], corner_points[1],
331 cv::Scalar(0, 0, 255), 2);
332 cv::line(color_image, corner_points[2], corner_points[1],
333 cv::Scalar(0, 0, 255), 2);
334 cv::line(color_image, corner_points[2], corner_points[3],
335 cv::Scalar(0, 0, 255), 2);
336 cv::line(color_image, corner_points[0], corner_points[3],
337 cv::Scalar(0, 0, 255), 2);
338 }
339
340 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
341 << " margin: " << det->decision_margin;
342
milind-u99b1a762023-03-12 16:48:32 -0700343 } else {
344 rejections_++;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800345 }
346 }
Jim Ostrowski49be8232023-03-23 01:00:14 -0700347 if (FLAGS_visualize) {
348 // Display the result
349 // Rotate by 180 degrees to make it upright
milind-ua30a4a12023-03-24 20:49:41 -0700350 if (flip_image_) {
351 cv::rotate(color_image, color_image, 1);
352 }
353 cv::imshow(absl::StrCat("AprilRoboticsDetector Image ", node_name_),
354 color_image);
Jim Ostrowski49be8232023-03-23 01:00:14 -0700355 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800356
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800357 const auto corners_offset = builder.fbb()->CreateVector(foxglove_corners);
Yash Chainani10b7b022023-02-22 14:34:04 -0800358 foxglove::ImageAnnotations::Builder annotation_builder(*builder.fbb());
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800359 annotation_builder.add_points(corners_offset);
360 builder.CheckOk(builder.Send(annotation_builder.Finish()));
Yash Chainani728ae222023-02-04 19:48:12 -0800361
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800362 apriltag_detections_destroy(detections);
363
364 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
365
milind-uf3ab8ba2023-02-04 17:56:16 -0800366 if (FLAGS_debug) {
367 timeprofile_display(tag_detector_->tp);
368 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800369
Austin Schuhd2667932023-02-04 16:22:39 -0800370 VLOG(1) << "Took " << chrono::duration<double>(end_time - start_time).count()
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800371 << " seconds to detect overall";
372
milind-u99b1a762023-03-12 16:48:32 -0700373 return {.detections = results, .rejections = rejections_};
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800374}
375
Stephan Pleinesf63bde82024-01-13 15:59:33 -0800376} // namespace y2023::vision