blob: b543dc72df90d22fc6e52630a36239ac293e1848 [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
milind-uc5a494f2023-02-24 15:39:22 -080011DEFINE_double(min_decision_margin, 75.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
Maxwell Hendersonfebee252023-01-28 16:53:52 -080023namespace y2023 {
24namespace vision {
25
Austin Schuhd2667932023-02-04 16:22:39 -080026namespace chrono = std::chrono;
27
Maxwell Hendersonfebee252023-01-28 16:53:52 -080028AprilRoboticsDetector::AprilRoboticsDetector(aos::EventLoop *event_loop,
milind-ua30a4a12023-03-24 20:49:41 -070029 std::string_view channel_name,
30 bool flip_image)
James Kuszmauld67f6d22023-02-05 17:37:25 -080031 : calibration_data_(event_loop),
milind-uf5b3b4b2023-02-26 14:50:38 -080032 image_size_(0, 0),
milind-ua30a4a12023-03-24 20:49:41 -070033 flip_image_(flip_image),
34 node_name_(event_loop->node()->name()->string_view()),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080035 ftrace_(),
milind-ua30a4a12023-03-24 20:49:41 -070036 image_callback_(
37 event_loop, channel_name,
38 [&](cv::Mat image_color_mat,
39 const aos::monotonic_clock::time_point eof) {
40 HandleImage(image_color_mat, eof);
41 },
42 chrono::milliseconds(5)),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080043 target_map_sender_(
Yash Chainani728ae222023-02-04 19:48:12 -080044 event_loop->MakeSender<frc971::vision::TargetMap>("/camera")),
milind-u7aa29e22023-02-23 20:22:01 -080045 image_annotations_sender_(
milind-u99b1a762023-03-12 16:48:32 -070046 event_loop->MakeSender<foxglove::ImageAnnotations>("/camera")),
47 rejections_(0) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080048 tag_family_ = tag16h5_create();
49 tag_detector_ = apriltag_detector_create();
50
51 apriltag_detector_add_family_bits(tag_detector_, tag_family_, 1);
52 tag_detector_->nthreads = 6;
53 tag_detector_->wp = workerpool_create(tag_detector_->nthreads);
54 tag_detector_->qtp.min_white_black_diff = 5;
55 tag_detector_->debug = FLAGS_debug;
56
57 std::string hostname = aos::network::GetHostname();
58
59 // Check team string is valid
James Kuszmauld67f6d22023-02-05 17:37:25 -080060 calibration_ = FindCameraCalibration(
61 calibration_data_.constants(), event_loop->node()->name()->string_view());
milind-uf2a4e322023-02-01 19:33:10 -080062
63 extrinsics_ = CameraExtrinsics(calibration_);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080064 intrinsics_ = CameraIntrinsics(calibration_);
milind-uf2a4e322023-02-01 19:33:10 -080065 // Create an undistort projection matrix using the intrinsics
66 projection_matrix_ = cv::Mat::zeros(3, 4, CV_64F);
67 intrinsics_.rowRange(0, 3).colRange(0, 3).copyTo(
68 projection_matrix_.rowRange(0, 3).colRange(0, 3));
69
70 dist_coeffs_ = CameraDistCoeffs(calibration_);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080071
72 image_callback_.set_format(frc971::vision::ImageCallback::Format::GRAYSCALE);
73}
74
75AprilRoboticsDetector::~AprilRoboticsDetector() {
76 apriltag_detector_destroy(tag_detector_);
77 free(tag_family_);
78}
79
80void AprilRoboticsDetector::SetWorkerpoolAffinities() {
81 for (int i = 0; i < tag_detector_->wp->nthreads; i++) {
82 cpu_set_t affinity;
83 CPU_ZERO(&affinity);
84 CPU_SET(i, &affinity);
85 pthread_setaffinity_np(tag_detector_->wp->threads[i], sizeof(affinity),
86 &affinity);
87 struct sched_param param;
88 param.sched_priority = 20;
89 int res = pthread_setschedparam(tag_detector_->wp->threads[i], SCHED_FIFO,
90 &param);
91 PCHECK(res == 0) << "Failed to set priority of threadpool threads";
92 }
93}
94
milind-uf2a4e322023-02-01 19:33:10 -080095void AprilRoboticsDetector::HandleImage(cv::Mat image_grayscale,
milind-u09fb1252023-01-28 19:21:41 -080096 aos::monotonic_clock::time_point eof) {
milind-uf5b3b4b2023-02-26 14:50:38 -080097 image_size_ = image_grayscale.size();
98
milind-u99b1a762023-03-12 16:48:32 -070099 DetectionResult result = DetectTags(image_grayscale, eof);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800100
101 auto builder = target_map_sender_.MakeBuilder();
102 std::vector<flatbuffers::Offset<frc971::vision::TargetPoseFbs>> target_poses;
milind-ude9045f2023-03-25 18:17:12 -0700103 for (auto &detection : result.detections) {
104 auto *fbb = builder.fbb();
105 auto pose = BuildTargetPose(detection, fbb);
106 DestroyPose(&detection.pose);
107 target_poses.emplace_back(pose);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800108 }
109 const auto target_poses_offset = builder.fbb()->CreateVector(target_poses);
110 auto target_map_builder = builder.MakeBuilder<frc971::vision::TargetMap>();
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800111 target_map_builder.add_target_poses(target_poses_offset);
milind-u09fb1252023-01-28 19:21:41 -0800112 target_map_builder.add_monotonic_timestamp_ns(eof.time_since_epoch().count());
milind-u99b1a762023-03-12 16:48:32 -0700113 target_map_builder.add_rejections(result.rejections);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800114 builder.CheckOk(builder.Send(target_map_builder.Finish()));
115}
116
117flatbuffers::Offset<frc971::vision::TargetPoseFbs>
milind-ufc8ab702023-02-26 14:14:39 -0800118AprilRoboticsDetector::BuildTargetPose(const Detection &detection,
milind-u681c4712023-02-23 21:22:50 -0800119 flatbuffers::FlatBufferBuilder *fbb) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800120 const auto T =
milind-ufc8ab702023-02-26 14:14:39 -0800121 Eigen::Translation3d(detection.pose.t->data[0], detection.pose.t->data[1],
122 detection.pose.t->data[2]);
milind-u3f5f83c2023-01-29 15:23:51 -0800123 const auto position_offset =
124 frc971::vision::CreatePosition(*fbb, T.x(), T.y(), T.z());
125
milind-u633c4c02023-02-25 22:51:45 -0800126 // Aprilrobotics stores the rotation matrix in row-major order
127 const auto orientation = Eigen::Quaterniond(
milind-ufc8ab702023-02-26 14:14:39 -0800128 Eigen::Matrix<double, 3, 3, Eigen::RowMajor>(detection.pose.R->data));
milind-u3f5f83c2023-01-29 15:23:51 -0800129 const auto orientation_offset = frc971::vision::CreateQuaternion(
130 *fbb, orientation.w(), orientation.x(), orientation.y(), orientation.z());
131
milind-u681c4712023-02-23 21:22:50 -0800132 return frc971::vision::CreateTargetPoseFbs(
milind-ufc8ab702023-02-26 14:14:39 -0800133 *fbb, detection.det.id, position_offset, orientation_offset,
milind-uf5b3b4b2023-02-26 14:50:38 -0800134 detection.det.decision_margin, detection.pose_error,
milind-ude9045f2023-03-25 18:17:12 -0700135 detection.distortion_factor, detection.pose_error_ratio);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800136}
137
milind-uf2a4e322023-02-01 19:33:10 -0800138void AprilRoboticsDetector::UndistortDetection(
139 apriltag_detection_t *det) const {
140 // 4 corners
141 constexpr size_t kRows = 4;
142 // 2d points
143 constexpr size_t kCols = 2;
144
145 cv::Mat distorted_points(kRows, kCols, CV_64F, det->p);
146 cv::Mat undistorted_points = cv::Mat::zeros(kRows, kCols, CV_64F);
147
148 // Undistort the april tag points
149 cv::undistortPoints(distorted_points, undistorted_points, intrinsics_,
150 dist_coeffs_, cv::noArray(), projection_matrix_);
151
152 // Copy the undistorted points into det
153 for (size_t i = 0; i < kRows; i++) {
154 for (size_t j = 0; j < kCols; j++) {
155 det->p[i][j] = undistorted_points.at<double>(i, j);
156 }
157 }
158}
159
milind-uf5b3b4b2023-02-26 14:50:38 -0800160double AprilRoboticsDetector::ComputeDistortionFactor(
161 const std::vector<cv::Point2f> &orig_corners,
162 const std::vector<cv::Point2f> &corners) {
163 CHECK_EQ(orig_corners.size(), 4ul);
164 CHECK_EQ(corners.size(), 4ul);
165
166 double avg_distance = 0.0;
167 for (size_t i = 0; i < corners.size(); i++) {
168 avg_distance += cv::norm(orig_corners[i] - corners[i]);
169 }
170 avg_distance /= corners.size();
171
milind-u8773c232023-03-11 14:59:06 -0800172 // Normalize avg_distance by dividing by the image diagonal,
173 // and then the maximum expected distortion
milind-uf5b3b4b2023-02-26 14:50:38 -0800174 double distortion_factor =
175 avg_distance /
milind-u8773c232023-03-11 14:59:06 -0800176 cv::norm(cv::Point2d(image_size_.width, image_size_.height));
milind-u60e7fe52023-02-26 16:13:50 -0800177 return std::min(distortion_factor / FLAGS_max_expected_distortion, 1.0);
milind-uf5b3b4b2023-02-26 14:50:38 -0800178}
179
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800180std::vector<cv::Point2f> AprilRoboticsDetector::MakeCornerVector(
181 const apriltag_detection_t *det) {
182 std::vector<cv::Point2f> corner_points;
183 corner_points.emplace_back(det->p[0][0], det->p[0][1]);
184 corner_points.emplace_back(det->p[1][0], det->p[1][1]);
185 corner_points.emplace_back(det->p[2][0], det->p[2][1]);
186 corner_points.emplace_back(det->p[3][0], det->p[3][1]);
187
188 return corner_points;
189}
190
milind-ude9045f2023-03-25 18:17:12 -0700191void AprilRoboticsDetector::DestroyPose(apriltag_pose_t *pose) const {
192 matd_destroy(pose->R);
193 matd_destroy(pose->t);
194}
195
milind-u99b1a762023-03-12 16:48:32 -0700196AprilRoboticsDetector::DetectionResult AprilRoboticsDetector::DetectTags(
milind-ufc8ab702023-02-26 14:14:39 -0800197 cv::Mat image, aos::monotonic_clock::time_point eof) {
Jim Ostrowski49be8232023-03-23 01:00:14 -0700198 cv::Mat color_image;
199 cvtColor(image, color_image, cv::COLOR_GRAY2RGB);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800200 const aos::monotonic_clock::time_point start_time =
201 aos::monotonic_clock::now();
202
203 image_u8_t im = {
milind-u09fb1252023-01-28 19:21:41 -0800204 .width = image.cols,
205 .height = image.rows,
206 .stride = image.cols,
207 .buf = image.data,
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800208 };
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800209 const uint32_t min_x = FLAGS_pixel_border;
210 const uint32_t max_x = image.cols - FLAGS_pixel_border;
Jim Ostrowski0197d6b2023-03-04 12:41:13 -0800211 const uint32_t min_y = FLAGS_pixel_border;
212 const uint32_t max_y = image.rows - FLAGS_pixel_border;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800213
214 ftrace_.FormatMessage("Starting detect\n");
215 zarray_t *detections = apriltag_detector_detect(tag_detector_, &im);
216 ftrace_.FormatMessage("Done detecting\n");
217
milind-ufc8ab702023-02-26 14:14:39 -0800218 std::vector<Detection> results;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800219
milind-u7aa29e22023-02-23 20:22:01 -0800220 auto builder = image_annotations_sender_.MakeBuilder();
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800221 std::vector<flatbuffers::Offset<foxglove::PointsAnnotation>> foxglove_corners;
Yash Chainani728ae222023-02-04 19:48:12 -0800222
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800223 for (int i = 0; i < zarray_size(detections); i++) {
224 apriltag_detection_t *det;
225 zarray_get(detections, i, &det);
226
milind-uf2a4e322023-02-01 19:33:10 -0800227 if (det->decision_margin > FLAGS_min_decision_margin) {
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800228 if (det->p[0][0] < min_x || det->p[0][0] > max_x ||
229 det->p[1][0] < min_x || det->p[1][0] > max_x ||
230 det->p[2][0] < min_x || det->p[2][0] > max_x ||
Jim Ostrowski0197d6b2023-03-04 12:41:13 -0800231 det->p[3][0] < min_x || det->p[3][0] > max_x ||
232 det->p[0][1] < min_y || det->p[0][1] > max_y ||
233 det->p[1][1] < min_y || det->p[1][1] > max_y ||
234 det->p[2][1] < min_y || det->p[2][1] > max_y ||
235 det->p[3][1] < min_y || det->p[3][1] > max_y) {
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800236 VLOG(1) << "Rejecting detection because corner is outside pixel border";
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800237 // Send rejected corner points in red
238 std::vector<cv::Point2f> rejected_corner_points = MakeCornerVector(det);
239 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
240 builder.fbb(), eof, rejected_corner_points,
241 std::vector<double>{1.0, 0.0, 0.0, 0.5}));
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800242 continue;
243 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800244 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
245 << " margin: " << det->decision_margin;
246
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800247 // First create an apriltag_detection_info_t struct using your known
248 // parameters.
249 apriltag_detection_info_t info;
250 info.det = det;
251 info.tagsize = 0.1524;
milind-uf2a4e322023-02-01 19:33:10 -0800252
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800253 info.fx = intrinsics_.at<double>(0, 0);
254 info.fy = intrinsics_.at<double>(1, 1);
255 info.cx = intrinsics_.at<double>(0, 2);
256 info.cy = intrinsics_.at<double>(1, 2);
257
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800258 // Send original corner points in green
259 std::vector<cv::Point2f> orig_corner_points = MakeCornerVector(det);
260 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
261 builder.fbb(), eof, orig_corner_points,
262 std::vector<double>{0.0, 1.0, 0.0, 0.5}));
Jim Ostrowskid2b5c912023-02-26 00:59:35 -0800263
milind-ueccac3c2023-02-25 20:54:47 -0800264 UndistortDetection(det);
265
milind-uf5b3b4b2023-02-26 14:50:38 -0800266 const aos::monotonic_clock::time_point before_pose_estimation =
267 aos::monotonic_clock::now();
268
milind-ude9045f2023-03-25 18:17:12 -0700269 apriltag_pose_t pose_1;
270 apriltag_pose_t pose_2;
271 double pose_error_1;
272 double pose_error_2;
273 estimate_tag_pose_orthogonal_iteration(&info, &pose_error_1, &pose_1,
274 &pose_error_2, &pose_2,
275 FLAGS_pose_estimation_iterations);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800276
277 const aos::monotonic_clock::time_point after_pose_estimation =
278 aos::monotonic_clock::now();
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800279 VLOG(1) << "Took "
Austin Schuhd2667932023-02-04 16:22:39 -0800280 << chrono::duration<double>(after_pose_estimation -
281 before_pose_estimation)
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800282 .count()
283 << " seconds for pose estimation";
milind-ude9045f2023-03-25 18:17:12 -0700284 VLOG(1) << "Pose err 1: " << pose_error_1;
285 VLOG(1) << "Pose err 2: " << pose_error_2;
Yash Chainani728ae222023-02-04 19:48:12 -0800286
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800287 // Send undistorted corner points in pink
288 std::vector<cv::Point2f> corner_points = MakeCornerVector(det);
289 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
290 builder.fbb(), eof, corner_points,
291 std::vector<double>{1.0, 0.75, 0.8, 1.0}));
milind-uf5b3b4b2023-02-26 14:50:38 -0800292
293 double distortion_factor =
294 ComputeDistortionFactor(orig_corner_points, corner_points);
295
milind-ude9045f2023-03-25 18:17:12 -0700296 // We get two estimates for poses.
297 // Choose the one with the lower estimation error
298 bool use_pose_1 = (pose_error_1 < pose_error_2);
299 auto best_pose = (use_pose_1 ? pose_1 : pose_2);
300 auto secondary_pose = (use_pose_1 ? pose_2 : pose_1);
301 double best_pose_error = (use_pose_1 ? pose_error_1 : pose_error_2);
302 double secondary_pose_error = (use_pose_1 ? pose_error_2 : pose_error_1);
303
304 CHECK_NE(best_pose_error, std::numeric_limits<double>::infinity())
305 << "Got no valid pose estimations, this should not be possible.";
306 double pose_error_ratio = best_pose_error / secondary_pose_error;
307
308 // Destroy the secondary pose if we got one
309 if (secondary_pose_error != std::numeric_limits<double>::infinity()) {
310 DestroyPose(&secondary_pose);
311 }
312
milind-uf5b3b4b2023-02-26 14:50:38 -0800313 results.emplace_back(Detection{.det = *det,
milind-ude9045f2023-03-25 18:17:12 -0700314 .pose = best_pose,
315 .pose_error = best_pose_error,
316 .distortion_factor = distortion_factor,
317 .pose_error_ratio = pose_error_ratio});
318
Jim Ostrowski49be8232023-03-23 01:00:14 -0700319 if (FLAGS_visualize) {
320 // Draw raw (distorted) corner points in green
321 cv::line(color_image, orig_corner_points[0], orig_corner_points[1],
322 cv::Scalar(0, 255, 0), 2);
323 cv::line(color_image, orig_corner_points[1], orig_corner_points[2],
324 cv::Scalar(0, 255, 0), 2);
325 cv::line(color_image, orig_corner_points[2], orig_corner_points[3],
326 cv::Scalar(0, 255, 0), 2);
327 cv::line(color_image, orig_corner_points[3], orig_corner_points[0],
328 cv::Scalar(0, 255, 0), 2);
329
330 // Draw undistorted corner points in red
331 cv::line(color_image, corner_points[0], corner_points[1],
332 cv::Scalar(0, 0, 255), 2);
333 cv::line(color_image, corner_points[2], corner_points[1],
334 cv::Scalar(0, 0, 255), 2);
335 cv::line(color_image, corner_points[2], corner_points[3],
336 cv::Scalar(0, 0, 255), 2);
337 cv::line(color_image, corner_points[0], corner_points[3],
338 cv::Scalar(0, 0, 255), 2);
339 }
340
341 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
342 << " margin: " << det->decision_margin;
343
milind-u99b1a762023-03-12 16:48:32 -0700344 } else {
345 rejections_++;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800346 }
347 }
Jim Ostrowski49be8232023-03-23 01:00:14 -0700348 if (FLAGS_visualize) {
349 // Display the result
350 // Rotate by 180 degrees to make it upright
milind-ua30a4a12023-03-24 20:49:41 -0700351 if (flip_image_) {
352 cv::rotate(color_image, color_image, 1);
353 }
354 cv::imshow(absl::StrCat("AprilRoboticsDetector Image ", node_name_),
355 color_image);
Jim Ostrowski49be8232023-03-23 01:00:14 -0700356 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800357
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800358 const auto corners_offset = builder.fbb()->CreateVector(foxglove_corners);
Yash Chainani10b7b022023-02-22 14:34:04 -0800359 foxglove::ImageAnnotations::Builder annotation_builder(*builder.fbb());
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800360 annotation_builder.add_points(corners_offset);
361 builder.CheckOk(builder.Send(annotation_builder.Finish()));
Yash Chainani728ae222023-02-04 19:48:12 -0800362
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800363 apriltag_detections_destroy(detections);
364
365 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
366
milind-uf3ab8ba2023-02-04 17:56:16 -0800367 if (FLAGS_debug) {
368 timeprofile_display(tag_detector_->tp);
369 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800370
Austin Schuhd2667932023-02-04 16:22:39 -0800371 VLOG(1) << "Took " << chrono::duration<double>(end_time - start_time).count()
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800372 << " seconds to detect overall";
373
milind-u99b1a762023-03-12 16:48:32 -0700374 return {.detections = results, .rejections = rejections_};
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800375}
376
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800377} // namespace vision
378} // namespace y2023