blob: 95ad541c6f520ea7e3a5dbc17a13dc99d079e066 [file] [log] [blame]
Maxwell Hendersonfebee252023-01-28 16:53:52 -08001#include "y2023/vision/aprilrobotics.h"
2
James Kuszmauld67f6d22023-02-05 17:37:25 -08003#include "y2023/vision/vision_util.h"
4
Maxwell Hendersonfebee252023-01-28 16:53:52 -08005DEFINE_bool(
6 debug, false,
7 "If true, dump a ton of debug and crash on the first valid detection.");
8
milind-uc5a494f2023-02-24 15:39:22 -08009DEFINE_double(min_decision_margin, 75.0,
milind-uf2a4e322023-02-01 19:33:10 -080010 "Minimum decision margin (confidence) for an apriltag detection");
Jim Ostrowski14124a32023-03-03 22:16:07 -080011DEFINE_int32(pixel_border, 10,
Jim Ostrowski437b1fb2023-02-26 10:12:01 -080012 "Size of image border within which to reject detected corners");
milind-u60e7fe52023-02-26 16:13:50 -080013DEFINE_double(
milind-u8773c232023-03-11 14:59:06 -080014 max_expected_distortion, 0.314,
milind-u60e7fe52023-02-26 16:13:50 -080015 "Maximum expected value for unscaled distortion factors. Will scale "
16 "distortion factors so that this value (and a higher distortion) maps to "
17 "1.0.");
milind-uf2a4e322023-02-01 19:33:10 -080018
Maxwell Hendersonfebee252023-01-28 16:53:52 -080019namespace y2023 {
20namespace vision {
21
Austin Schuhd2667932023-02-04 16:22:39 -080022namespace chrono = std::chrono;
23
Maxwell Hendersonfebee252023-01-28 16:53:52 -080024AprilRoboticsDetector::AprilRoboticsDetector(aos::EventLoop *event_loop,
25 std::string_view channel_name)
James Kuszmauld67f6d22023-02-05 17:37:25 -080026 : calibration_data_(event_loop),
milind-uf5b3b4b2023-02-26 14:50:38 -080027 image_size_(0, 0),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080028 ftrace_(),
Yash Chainani10b7b022023-02-22 14:34:04 -080029 image_callback_(
30 event_loop, channel_name,
31 [&](cv::Mat image_color_mat,
32 const aos::monotonic_clock::time_point eof) {
33 HandleImage(image_color_mat, eof);
34 },
35 chrono::milliseconds(5)),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080036 target_map_sender_(
Yash Chainani728ae222023-02-04 19:48:12 -080037 event_loop->MakeSender<frc971::vision::TargetMap>("/camera")),
milind-u7aa29e22023-02-23 20:22:01 -080038 image_annotations_sender_(
milind-u99b1a762023-03-12 16:48:32 -070039 event_loop->MakeSender<foxglove::ImageAnnotations>("/camera")),
40 rejections_(0) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080041 tag_family_ = tag16h5_create();
42 tag_detector_ = apriltag_detector_create();
43
44 apriltag_detector_add_family_bits(tag_detector_, tag_family_, 1);
45 tag_detector_->nthreads = 6;
46 tag_detector_->wp = workerpool_create(tag_detector_->nthreads);
47 tag_detector_->qtp.min_white_black_diff = 5;
48 tag_detector_->debug = FLAGS_debug;
49
50 std::string hostname = aos::network::GetHostname();
51
52 // Check team string is valid
James Kuszmauld67f6d22023-02-05 17:37:25 -080053 calibration_ = FindCameraCalibration(
54 calibration_data_.constants(), event_loop->node()->name()->string_view());
milind-uf2a4e322023-02-01 19:33:10 -080055
56 extrinsics_ = CameraExtrinsics(calibration_);
57
Maxwell Hendersonfebee252023-01-28 16:53:52 -080058 intrinsics_ = CameraIntrinsics(calibration_);
milind-uf2a4e322023-02-01 19:33:10 -080059 // Create an undistort projection matrix using the intrinsics
60 projection_matrix_ = cv::Mat::zeros(3, 4, CV_64F);
61 intrinsics_.rowRange(0, 3).colRange(0, 3).copyTo(
62 projection_matrix_.rowRange(0, 3).colRange(0, 3));
63
64 dist_coeffs_ = CameraDistCoeffs(calibration_);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080065
66 image_callback_.set_format(frc971::vision::ImageCallback::Format::GRAYSCALE);
67}
68
69AprilRoboticsDetector::~AprilRoboticsDetector() {
70 apriltag_detector_destroy(tag_detector_);
71 free(tag_family_);
72}
73
74void AprilRoboticsDetector::SetWorkerpoolAffinities() {
75 for (int i = 0; i < tag_detector_->wp->nthreads; i++) {
76 cpu_set_t affinity;
77 CPU_ZERO(&affinity);
78 CPU_SET(i, &affinity);
79 pthread_setaffinity_np(tag_detector_->wp->threads[i], sizeof(affinity),
80 &affinity);
81 struct sched_param param;
82 param.sched_priority = 20;
83 int res = pthread_setschedparam(tag_detector_->wp->threads[i], SCHED_FIFO,
84 &param);
85 PCHECK(res == 0) << "Failed to set priority of threadpool threads";
86 }
87}
88
milind-uf2a4e322023-02-01 19:33:10 -080089void AprilRoboticsDetector::HandleImage(cv::Mat image_grayscale,
milind-u09fb1252023-01-28 19:21:41 -080090 aos::monotonic_clock::time_point eof) {
milind-uf5b3b4b2023-02-26 14:50:38 -080091 image_size_ = image_grayscale.size();
92
milind-u99b1a762023-03-12 16:48:32 -070093 DetectionResult result = DetectTags(image_grayscale, eof);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080094
95 auto builder = target_map_sender_.MakeBuilder();
96 std::vector<flatbuffers::Offset<frc971::vision::TargetPoseFbs>> target_poses;
milind-u99b1a762023-03-12 16:48:32 -070097 for (const auto &detection : result.detections) {
milind-ufc8ab702023-02-26 14:14:39 -080098 target_poses.emplace_back(BuildTargetPose(detection, builder.fbb()));
Maxwell Hendersonfebee252023-01-28 16:53:52 -080099 }
100 const auto target_poses_offset = builder.fbb()->CreateVector(target_poses);
101 auto target_map_builder = builder.MakeBuilder<frc971::vision::TargetMap>();
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800102 target_map_builder.add_target_poses(target_poses_offset);
milind-u09fb1252023-01-28 19:21:41 -0800103 target_map_builder.add_monotonic_timestamp_ns(eof.time_since_epoch().count());
milind-u99b1a762023-03-12 16:48:32 -0700104 target_map_builder.add_rejections(result.rejections);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800105 builder.CheckOk(builder.Send(target_map_builder.Finish()));
106}
107
108flatbuffers::Offset<frc971::vision::TargetPoseFbs>
milind-ufc8ab702023-02-26 14:14:39 -0800109AprilRoboticsDetector::BuildTargetPose(const Detection &detection,
milind-u681c4712023-02-23 21:22:50 -0800110 flatbuffers::FlatBufferBuilder *fbb) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800111 const auto T =
milind-ufc8ab702023-02-26 14:14:39 -0800112 Eigen::Translation3d(detection.pose.t->data[0], detection.pose.t->data[1],
113 detection.pose.t->data[2]);
milind-u3f5f83c2023-01-29 15:23:51 -0800114 const auto position_offset =
115 frc971::vision::CreatePosition(*fbb, T.x(), T.y(), T.z());
116
milind-u633c4c02023-02-25 22:51:45 -0800117 // Aprilrobotics stores the rotation matrix in row-major order
118 const auto orientation = Eigen::Quaterniond(
milind-ufc8ab702023-02-26 14:14:39 -0800119 Eigen::Matrix<double, 3, 3, Eigen::RowMajor>(detection.pose.R->data));
milind-u3f5f83c2023-01-29 15:23:51 -0800120 const auto orientation_offset = frc971::vision::CreateQuaternion(
121 *fbb, orientation.w(), orientation.x(), orientation.y(), orientation.z());
122
milind-u681c4712023-02-23 21:22:50 -0800123 return frc971::vision::CreateTargetPoseFbs(
milind-ufc8ab702023-02-26 14:14:39 -0800124 *fbb, detection.det.id, position_offset, orientation_offset,
milind-uf5b3b4b2023-02-26 14:50:38 -0800125 detection.det.decision_margin, detection.pose_error,
126 detection.distortion_factor);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800127}
128
milind-uf2a4e322023-02-01 19:33:10 -0800129void AprilRoboticsDetector::UndistortDetection(
130 apriltag_detection_t *det) const {
131 // 4 corners
132 constexpr size_t kRows = 4;
133 // 2d points
134 constexpr size_t kCols = 2;
135
136 cv::Mat distorted_points(kRows, kCols, CV_64F, det->p);
137 cv::Mat undistorted_points = cv::Mat::zeros(kRows, kCols, CV_64F);
138
139 // Undistort the april tag points
140 cv::undistortPoints(distorted_points, undistorted_points, intrinsics_,
141 dist_coeffs_, cv::noArray(), projection_matrix_);
142
143 // Copy the undistorted points into det
144 for (size_t i = 0; i < kRows; i++) {
145 for (size_t j = 0; j < kCols; j++) {
146 det->p[i][j] = undistorted_points.at<double>(i, j);
147 }
148 }
149}
150
milind-uf5b3b4b2023-02-26 14:50:38 -0800151double AprilRoboticsDetector::ComputeDistortionFactor(
152 const std::vector<cv::Point2f> &orig_corners,
153 const std::vector<cv::Point2f> &corners) {
154 CHECK_EQ(orig_corners.size(), 4ul);
155 CHECK_EQ(corners.size(), 4ul);
156
157 double avg_distance = 0.0;
158 for (size_t i = 0; i < corners.size(); i++) {
159 avg_distance += cv::norm(orig_corners[i] - corners[i]);
160 }
161 avg_distance /= corners.size();
162
milind-u8773c232023-03-11 14:59:06 -0800163 // Normalize avg_distance by dividing by the image diagonal,
164 // and then the maximum expected distortion
milind-uf5b3b4b2023-02-26 14:50:38 -0800165 double distortion_factor =
166 avg_distance /
milind-u8773c232023-03-11 14:59:06 -0800167 cv::norm(cv::Point2d(image_size_.width, image_size_.height));
milind-u60e7fe52023-02-26 16:13:50 -0800168 return std::min(distortion_factor / FLAGS_max_expected_distortion, 1.0);
milind-uf5b3b4b2023-02-26 14:50:38 -0800169}
170
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800171std::vector<cv::Point2f> AprilRoboticsDetector::MakeCornerVector(
172 const apriltag_detection_t *det) {
173 std::vector<cv::Point2f> corner_points;
174 corner_points.emplace_back(det->p[0][0], det->p[0][1]);
175 corner_points.emplace_back(det->p[1][0], det->p[1][1]);
176 corner_points.emplace_back(det->p[2][0], det->p[2][1]);
177 corner_points.emplace_back(det->p[3][0], det->p[3][1]);
178
179 return corner_points;
180}
181
milind-u99b1a762023-03-12 16:48:32 -0700182AprilRoboticsDetector::DetectionResult AprilRoboticsDetector::DetectTags(
milind-ufc8ab702023-02-26 14:14:39 -0800183 cv::Mat image, aos::monotonic_clock::time_point eof) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800184 const aos::monotonic_clock::time_point start_time =
185 aos::monotonic_clock::now();
186
187 image_u8_t im = {
milind-u09fb1252023-01-28 19:21:41 -0800188 .width = image.cols,
189 .height = image.rows,
190 .stride = image.cols,
191 .buf = image.data,
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800192 };
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800193 const uint32_t min_x = FLAGS_pixel_border;
194 const uint32_t max_x = image.cols - FLAGS_pixel_border;
Jim Ostrowski0197d6b2023-03-04 12:41:13 -0800195 const uint32_t min_y = FLAGS_pixel_border;
196 const uint32_t max_y = image.rows - FLAGS_pixel_border;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800197
198 ftrace_.FormatMessage("Starting detect\n");
199 zarray_t *detections = apriltag_detector_detect(tag_detector_, &im);
200 ftrace_.FormatMessage("Done detecting\n");
201
milind-ufc8ab702023-02-26 14:14:39 -0800202 std::vector<Detection> results;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800203
milind-u7aa29e22023-02-23 20:22:01 -0800204 auto builder = image_annotations_sender_.MakeBuilder();
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800205 std::vector<flatbuffers::Offset<foxglove::PointsAnnotation>> foxglove_corners;
Yash Chainani728ae222023-02-04 19:48:12 -0800206
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800207 for (int i = 0; i < zarray_size(detections); i++) {
208 apriltag_detection_t *det;
209 zarray_get(detections, i, &det);
210
milind-uf2a4e322023-02-01 19:33:10 -0800211 if (det->decision_margin > FLAGS_min_decision_margin) {
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800212 if (det->p[0][0] < min_x || det->p[0][0] > max_x ||
213 det->p[1][0] < min_x || det->p[1][0] > max_x ||
214 det->p[2][0] < min_x || det->p[2][0] > max_x ||
Jim Ostrowski0197d6b2023-03-04 12:41:13 -0800215 det->p[3][0] < min_x || det->p[3][0] > max_x ||
216 det->p[0][1] < min_y || det->p[0][1] > max_y ||
217 det->p[1][1] < min_y || det->p[1][1] > max_y ||
218 det->p[2][1] < min_y || det->p[2][1] > max_y ||
219 det->p[3][1] < min_y || det->p[3][1] > max_y) {
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800220 VLOG(1) << "Rejecting detection because corner is outside pixel border";
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800221 // Send rejected corner points in red
222 std::vector<cv::Point2f> rejected_corner_points = MakeCornerVector(det);
223 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
224 builder.fbb(), eof, rejected_corner_points,
225 std::vector<double>{1.0, 0.0, 0.0, 0.5}));
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800226 continue;
227 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800228 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
229 << " margin: " << det->decision_margin;
230
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800231 // First create an apriltag_detection_info_t struct using your known
232 // parameters.
233 apriltag_detection_info_t info;
234 info.det = det;
235 info.tagsize = 0.1524;
milind-uf2a4e322023-02-01 19:33:10 -0800236
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800237 info.fx = intrinsics_.at<double>(0, 0);
238 info.fy = intrinsics_.at<double>(1, 1);
239 info.cx = intrinsics_.at<double>(0, 2);
240 info.cy = intrinsics_.at<double>(1, 2);
241
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800242 // Send original corner points in green
243 std::vector<cv::Point2f> orig_corner_points = MakeCornerVector(det);
244 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
245 builder.fbb(), eof, orig_corner_points,
246 std::vector<double>{0.0, 1.0, 0.0, 0.5}));
Jim Ostrowskid2b5c912023-02-26 00:59:35 -0800247
milind-ueccac3c2023-02-25 20:54:47 -0800248 UndistortDetection(det);
249
milind-uf5b3b4b2023-02-26 14:50:38 -0800250 const aos::monotonic_clock::time_point before_pose_estimation =
251 aos::monotonic_clock::now();
252
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800253 apriltag_pose_t pose;
milind-uf5b3b4b2023-02-26 14:50:38 -0800254 double pose_error = estimate_tag_pose(&info, &pose);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800255
256 const aos::monotonic_clock::time_point after_pose_estimation =
257 aos::monotonic_clock::now();
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800258 VLOG(1) << "Took "
Austin Schuhd2667932023-02-04 16:22:39 -0800259 << chrono::duration<double>(after_pose_estimation -
260 before_pose_estimation)
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800261 .count()
262 << " seconds for pose estimation";
milind-uf5b3b4b2023-02-26 14:50:38 -0800263 VLOG(1) << "Pose err: " << pose_error;
Yash Chainani728ae222023-02-04 19:48:12 -0800264
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800265 // Send undistorted corner points in pink
266 std::vector<cv::Point2f> corner_points = MakeCornerVector(det);
267 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
268 builder.fbb(), eof, corner_points,
269 std::vector<double>{1.0, 0.75, 0.8, 1.0}));
milind-uf5b3b4b2023-02-26 14:50:38 -0800270
271 double distortion_factor =
272 ComputeDistortionFactor(orig_corner_points, corner_points);
273
274 results.emplace_back(Detection{.det = *det,
275 .pose = pose,
276 .pose_error = pose_error,
277 .distortion_factor = distortion_factor});
milind-u99b1a762023-03-12 16:48:32 -0700278 } else {
279 rejections_++;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800280 }
281 }
282
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800283 const auto corners_offset = builder.fbb()->CreateVector(foxglove_corners);
Yash Chainani10b7b022023-02-22 14:34:04 -0800284 foxglove::ImageAnnotations::Builder annotation_builder(*builder.fbb());
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800285 annotation_builder.add_points(corners_offset);
286 builder.CheckOk(builder.Send(annotation_builder.Finish()));
Yash Chainani728ae222023-02-04 19:48:12 -0800287
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800288 apriltag_detections_destroy(detections);
289
290 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
291
milind-uf3ab8ba2023-02-04 17:56:16 -0800292 if (FLAGS_debug) {
293 timeprofile_display(tag_detector_->tp);
294 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800295
Austin Schuhd2667932023-02-04 16:22:39 -0800296 VLOG(1) << "Took " << chrono::duration<double>(end_time - start_time).count()
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800297 << " seconds to detect overall";
298
milind-u99b1a762023-03-12 16:48:32 -0700299 return {.detections = results, .rejections = rejections_};
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800300}
301
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800302} // namespace vision
303} // namespace y2023