blob: c9c29e85adb5663a4345de9992625c41ab959fb2 [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");
11
Maxwell Hendersonfebee252023-01-28 16:53:52 -080012namespace y2023 {
13namespace vision {
14
Austin Schuhd2667932023-02-04 16:22:39 -080015namespace chrono = std::chrono;
16
Maxwell Hendersonfebee252023-01-28 16:53:52 -080017AprilRoboticsDetector::AprilRoboticsDetector(aos::EventLoop *event_loop,
18 std::string_view channel_name)
James Kuszmauld67f6d22023-02-05 17:37:25 -080019 : calibration_data_(event_loop),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080020 ftrace_(),
Jim Ostrowskid2b5c912023-02-26 00:59:35 -080021 image_callback_(event_loop, channel_name,
22 [&](cv::Mat image_color_mat,
23 const aos::monotonic_clock::time_point eof) {
24 HandleImage(image_color_mat, eof);
25 },
26 chrono::milliseconds(5)),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080027 target_map_sender_(
Yash Chainani728ae222023-02-04 19:48:12 -080028 event_loop->MakeSender<frc971::vision::TargetMap>("/camera")),
milind-u7aa29e22023-02-23 20:22:01 -080029 image_annotations_sender_(
30 event_loop->MakeSender<foxglove::ImageAnnotations>("/camera")) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080031 tag_family_ = tag16h5_create();
32 tag_detector_ = apriltag_detector_create();
33
34 apriltag_detector_add_family_bits(tag_detector_, tag_family_, 1);
35 tag_detector_->nthreads = 6;
36 tag_detector_->wp = workerpool_create(tag_detector_->nthreads);
37 tag_detector_->qtp.min_white_black_diff = 5;
38 tag_detector_->debug = FLAGS_debug;
39
40 std::string hostname = aos::network::GetHostname();
41
42 // Check team string is valid
James Kuszmauld67f6d22023-02-05 17:37:25 -080043 calibration_ = FindCameraCalibration(
44 calibration_data_.constants(), event_loop->node()->name()->string_view());
milind-uf2a4e322023-02-01 19:33:10 -080045
46 extrinsics_ = CameraExtrinsics(calibration_);
47
Maxwell Hendersonfebee252023-01-28 16:53:52 -080048 intrinsics_ = CameraIntrinsics(calibration_);
milind-uf2a4e322023-02-01 19:33:10 -080049 // Create an undistort projection matrix using the intrinsics
50 projection_matrix_ = cv::Mat::zeros(3, 4, CV_64F);
51 intrinsics_.rowRange(0, 3).colRange(0, 3).copyTo(
52 projection_matrix_.rowRange(0, 3).colRange(0, 3));
53
54 dist_coeffs_ = CameraDistCoeffs(calibration_);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080055
56 image_callback_.set_format(frc971::vision::ImageCallback::Format::GRAYSCALE);
57}
58
59AprilRoboticsDetector::~AprilRoboticsDetector() {
60 apriltag_detector_destroy(tag_detector_);
61 free(tag_family_);
62}
63
64void AprilRoboticsDetector::SetWorkerpoolAffinities() {
65 for (int i = 0; i < tag_detector_->wp->nthreads; i++) {
66 cpu_set_t affinity;
67 CPU_ZERO(&affinity);
68 CPU_SET(i, &affinity);
69 pthread_setaffinity_np(tag_detector_->wp->threads[i], sizeof(affinity),
70 &affinity);
71 struct sched_param param;
72 param.sched_priority = 20;
73 int res = pthread_setschedparam(tag_detector_->wp->threads[i], SCHED_FIFO,
74 &param);
75 PCHECK(res == 0) << "Failed to set priority of threadpool threads";
76 }
77}
78
milind-uf2a4e322023-02-01 19:33:10 -080079void AprilRoboticsDetector::HandleImage(cv::Mat image_grayscale,
milind-u09fb1252023-01-28 19:21:41 -080080 aos::monotonic_clock::time_point eof) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080081 std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>> detections =
milind-u7aa29e22023-02-23 20:22:01 -080082 DetectTags(image_grayscale, eof);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080083
84 auto builder = target_map_sender_.MakeBuilder();
85 std::vector<flatbuffers::Offset<frc971::vision::TargetPoseFbs>> target_poses;
86 for (const auto &[detection, pose] : detections) {
milind-u681c4712023-02-23 21:22:50 -080087 target_poses.emplace_back(BuildTargetPose(pose, detection, builder.fbb()));
Maxwell Hendersonfebee252023-01-28 16:53:52 -080088 }
89 const auto target_poses_offset = builder.fbb()->CreateVector(target_poses);
90 auto target_map_builder = builder.MakeBuilder<frc971::vision::TargetMap>();
Maxwell Hendersonfebee252023-01-28 16:53:52 -080091 target_map_builder.add_target_poses(target_poses_offset);
milind-u09fb1252023-01-28 19:21:41 -080092 target_map_builder.add_monotonic_timestamp_ns(eof.time_since_epoch().count());
Maxwell Hendersonfebee252023-01-28 16:53:52 -080093 builder.CheckOk(builder.Send(target_map_builder.Finish()));
94}
95
96flatbuffers::Offset<frc971::vision::TargetPoseFbs>
milind-u681c4712023-02-23 21:22:50 -080097AprilRoboticsDetector::BuildTargetPose(const apriltag_pose_t &pose,
98 const apriltag_detection_t &det,
99 flatbuffers::FlatBufferBuilder *fbb) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800100 const auto T =
101 Eigen::Translation3d(pose.t->data[0], pose.t->data[1], pose.t->data[2]);
milind-u3f5f83c2023-01-29 15:23:51 -0800102 const auto position_offset =
103 frc971::vision::CreatePosition(*fbb, T.x(), T.y(), T.z());
104
milind-u633c4c02023-02-25 22:51:45 -0800105 // Aprilrobotics stores the rotation matrix in row-major order
106 const auto orientation = Eigen::Quaterniond(
107 Eigen::Matrix<double, 3, 3, Eigen::RowMajor>(pose.R->data));
milind-u3f5f83c2023-01-29 15:23:51 -0800108 const auto orientation_offset = frc971::vision::CreateQuaternion(
109 *fbb, orientation.w(), orientation.x(), orientation.y(), orientation.z());
110
milind-u681c4712023-02-23 21:22:50 -0800111 return frc971::vision::CreateTargetPoseFbs(
112 *fbb, det.id, position_offset, orientation_offset, det.decision_margin);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800113}
114
milind-uf2a4e322023-02-01 19:33:10 -0800115void AprilRoboticsDetector::UndistortDetection(
116 apriltag_detection_t *det) const {
117 // 4 corners
118 constexpr size_t kRows = 4;
119 // 2d points
120 constexpr size_t kCols = 2;
121
122 cv::Mat distorted_points(kRows, kCols, CV_64F, det->p);
123 cv::Mat undistorted_points = cv::Mat::zeros(kRows, kCols, CV_64F);
124
125 // Undistort the april tag points
126 cv::undistortPoints(distorted_points, undistorted_points, intrinsics_,
127 dist_coeffs_, cv::noArray(), projection_matrix_);
128
129 // Copy the undistorted points into det
130 for (size_t i = 0; i < kRows; i++) {
131 for (size_t j = 0; j < kCols; j++) {
132 det->p[i][j] = undistorted_points.at<double>(i, j);
133 }
134 }
135}
136
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800137std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>>
milind-u7aa29e22023-02-23 20:22:01 -0800138AprilRoboticsDetector::DetectTags(cv::Mat image,
139 aos::monotonic_clock::time_point eof) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800140 const aos::monotonic_clock::time_point start_time =
141 aos::monotonic_clock::now();
142
143 image_u8_t im = {
milind-u09fb1252023-01-28 19:21:41 -0800144 .width = image.cols,
145 .height = image.rows,
146 .stride = image.cols,
147 .buf = image.data,
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800148 };
149
150 ftrace_.FormatMessage("Starting detect\n");
151 zarray_t *detections = apriltag_detector_detect(tag_detector_, &im);
152 ftrace_.FormatMessage("Done detecting\n");
153
154 std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>> results;
155
Jim Ostrowskid2b5c912023-02-26 00:59:35 -0800156 std::vector<std::vector<cv::Point2f>> orig_corners_vector;
milind-u7aa29e22023-02-23 20:22:01 -0800157 std::vector<std::vector<cv::Point2f>> corners_vector;
Yash Chainani728ae222023-02-04 19:48:12 -0800158
milind-u7aa29e22023-02-23 20:22:01 -0800159 auto builder = image_annotations_sender_.MakeBuilder();
Yash Chainani728ae222023-02-04 19:48:12 -0800160
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800161 for (int i = 0; i < zarray_size(detections); i++) {
162 apriltag_detection_t *det;
163 zarray_get(detections, i, &det);
164
milind-uf2a4e322023-02-01 19:33:10 -0800165 if (det->decision_margin > FLAGS_min_decision_margin) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800166 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
167 << " margin: " << det->decision_margin;
168
169 const aos::monotonic_clock::time_point before_pose_estimation =
170 aos::monotonic_clock::now();
171 // First create an apriltag_detection_info_t struct using your known
172 // parameters.
173 apriltag_detection_info_t info;
174 info.det = det;
175 info.tagsize = 0.1524;
milind-uf2a4e322023-02-01 19:33:10 -0800176
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800177 info.fx = intrinsics_.at<double>(0, 0);
178 info.fy = intrinsics_.at<double>(1, 1);
179 info.cx = intrinsics_.at<double>(0, 2);
180 info.cy = intrinsics_.at<double>(1, 2);
181
Jim Ostrowskid2b5c912023-02-26 00:59:35 -0800182 // Store out the original, pre-undistortion corner points for sending
183 std::vector<cv::Point2f> orig_corner_points;
184 orig_corner_points.emplace_back(det->p[0][0], det->p[0][1]);
185 orig_corner_points.emplace_back(det->p[1][0], det->p[1][1]);
186 orig_corner_points.emplace_back(det->p[2][0], det->p[2][1]);
187 orig_corner_points.emplace_back(det->p[3][0], det->p[3][1]);
188
189 orig_corners_vector.emplace_back(orig_corner_points);
190
milind-ueccac3c2023-02-25 20:54:47 -0800191 UndistortDetection(det);
192
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800193 apriltag_pose_t pose;
194 double err = estimate_tag_pose(&info, &pose);
195
196 VLOG(1) << "err: " << err;
197
198 results.emplace_back(*det, pose);
199
200 const aos::monotonic_clock::time_point after_pose_estimation =
201 aos::monotonic_clock::now();
202
203 VLOG(1) << "Took "
Austin Schuhd2667932023-02-04 16:22:39 -0800204 << chrono::duration<double>(after_pose_estimation -
205 before_pose_estimation)
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800206 .count()
207 << " seconds for pose estimation";
Yash Chainani728ae222023-02-04 19:48:12 -0800208
milind-u7aa29e22023-02-23 20:22:01 -0800209 std::vector<cv::Point2f> corner_points;
Yash Chainani728ae222023-02-04 19:48:12 -0800210 corner_points.emplace_back(det->p[0][0], det->p[0][1]);
211 corner_points.emplace_back(det->p[1][0], det->p[1][1]);
212 corner_points.emplace_back(det->p[2][0], det->p[2][1]);
213 corner_points.emplace_back(det->p[3][0], det->p[3][1]);
214
milind-u7aa29e22023-02-23 20:22:01 -0800215 corners_vector.emplace_back(corner_points);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800216 }
217 }
218
Jim Ostrowskid2b5c912023-02-26 00:59:35 -0800219 const auto annotations_offset = frc971::vision::BuildAnnotations(
220 eof, orig_corners_vector, 5.0, builder.fbb());
milind-u7aa29e22023-02-23 20:22:01 -0800221 builder.CheckOk(builder.Send(annotations_offset));
Yash Chainani728ae222023-02-04 19:48:12 -0800222
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800223 apriltag_detections_destroy(detections);
224
225 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
226
milind-uf3ab8ba2023-02-04 17:56:16 -0800227 if (FLAGS_debug) {
228 timeprofile_display(tag_detector_->tp);
229 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800230
Austin Schuhd2667932023-02-04 16:22:39 -0800231 VLOG(1) << "Took " << chrono::duration<double>(end_time - start_time).count()
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800232 << " seconds to detect overall";
233
234 return results;
235}
236
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800237} // namespace vision
238} // namespace y2023