blob: 7ccde65ee939f85f771a99d11ac7735ad13890cd [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_(),
Austin Schuhd2667932023-02-04 16:22:39 -080021 image_callback_(
22 event_loop, channel_name,
23 [&](cv::Mat image_color_mat,
24 const aos::monotonic_clock::time_point eof) {
25 HandleImage(image_color_mat, eof);
26 },
27 chrono::milliseconds(5)),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080028 target_map_sender_(
Yash Chainani728ae222023-02-04 19:48:12 -080029 event_loop->MakeSender<frc971::vision::TargetMap>("/camera")),
milind-u7aa29e22023-02-23 20:22:01 -080030 image_annotations_sender_(
31 event_loop->MakeSender<foxglove::ImageAnnotations>("/camera")) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080032 tag_family_ = tag16h5_create();
33 tag_detector_ = apriltag_detector_create();
34
35 apriltag_detector_add_family_bits(tag_detector_, tag_family_, 1);
36 tag_detector_->nthreads = 6;
37 tag_detector_->wp = workerpool_create(tag_detector_->nthreads);
38 tag_detector_->qtp.min_white_black_diff = 5;
39 tag_detector_->debug = FLAGS_debug;
40
41 std::string hostname = aos::network::GetHostname();
42
43 // Check team string is valid
James Kuszmauld67f6d22023-02-05 17:37:25 -080044 calibration_ = FindCameraCalibration(
45 calibration_data_.constants(), event_loop->node()->name()->string_view());
milind-uf2a4e322023-02-01 19:33:10 -080046
47 extrinsics_ = CameraExtrinsics(calibration_);
48
Maxwell Hendersonfebee252023-01-28 16:53:52 -080049 intrinsics_ = CameraIntrinsics(calibration_);
milind-uf2a4e322023-02-01 19:33:10 -080050 // Create an undistort projection matrix using the intrinsics
51 projection_matrix_ = cv::Mat::zeros(3, 4, CV_64F);
52 intrinsics_.rowRange(0, 3).colRange(0, 3).copyTo(
53 projection_matrix_.rowRange(0, 3).colRange(0, 3));
54
55 dist_coeffs_ = CameraDistCoeffs(calibration_);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080056
57 image_callback_.set_format(frc971::vision::ImageCallback::Format::GRAYSCALE);
58}
59
60AprilRoboticsDetector::~AprilRoboticsDetector() {
61 apriltag_detector_destroy(tag_detector_);
62 free(tag_family_);
63}
64
65void AprilRoboticsDetector::SetWorkerpoolAffinities() {
66 for (int i = 0; i < tag_detector_->wp->nthreads; i++) {
67 cpu_set_t affinity;
68 CPU_ZERO(&affinity);
69 CPU_SET(i, &affinity);
70 pthread_setaffinity_np(tag_detector_->wp->threads[i], sizeof(affinity),
71 &affinity);
72 struct sched_param param;
73 param.sched_priority = 20;
74 int res = pthread_setschedparam(tag_detector_->wp->threads[i], SCHED_FIFO,
75 &param);
76 PCHECK(res == 0) << "Failed to set priority of threadpool threads";
77 }
78}
79
milind-uf2a4e322023-02-01 19:33:10 -080080void AprilRoboticsDetector::HandleImage(cv::Mat image_grayscale,
milind-u09fb1252023-01-28 19:21:41 -080081 aos::monotonic_clock::time_point eof) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080082 std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>> detections =
milind-u7aa29e22023-02-23 20:22:01 -080083 DetectTags(image_grayscale, eof);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080084
85 auto builder = target_map_sender_.MakeBuilder();
86 std::vector<flatbuffers::Offset<frc971::vision::TargetPoseFbs>> target_poses;
87 for (const auto &[detection, pose] : detections) {
milind-u681c4712023-02-23 21:22:50 -080088 target_poses.emplace_back(BuildTargetPose(pose, detection, builder.fbb()));
Maxwell Hendersonfebee252023-01-28 16:53:52 -080089 }
90 const auto target_poses_offset = builder.fbb()->CreateVector(target_poses);
91 auto target_map_builder = builder.MakeBuilder<frc971::vision::TargetMap>();
Maxwell Hendersonfebee252023-01-28 16:53:52 -080092 target_map_builder.add_target_poses(target_poses_offset);
milind-u09fb1252023-01-28 19:21:41 -080093 target_map_builder.add_monotonic_timestamp_ns(eof.time_since_epoch().count());
Maxwell Hendersonfebee252023-01-28 16:53:52 -080094 builder.CheckOk(builder.Send(target_map_builder.Finish()));
95}
96
97flatbuffers::Offset<frc971::vision::TargetPoseFbs>
milind-u681c4712023-02-23 21:22:50 -080098AprilRoboticsDetector::BuildTargetPose(const apriltag_pose_t &pose,
99 const apriltag_detection_t &det,
100 flatbuffers::FlatBufferBuilder *fbb) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800101 const auto T =
102 Eigen::Translation3d(pose.t->data[0], pose.t->data[1], pose.t->data[2]);
milind-u3f5f83c2023-01-29 15:23:51 -0800103 const auto position_offset =
104 frc971::vision::CreatePosition(*fbb, T.x(), T.y(), T.z());
105
milind-u633c4c02023-02-25 22:51:45 -0800106 // Aprilrobotics stores the rotation matrix in row-major order
107 const auto orientation = Eigen::Quaterniond(
108 Eigen::Matrix<double, 3, 3, Eigen::RowMajor>(pose.R->data));
milind-u3f5f83c2023-01-29 15:23:51 -0800109 const auto orientation_offset = frc971::vision::CreateQuaternion(
110 *fbb, orientation.w(), orientation.x(), orientation.y(), orientation.z());
111
milind-u681c4712023-02-23 21:22:50 -0800112 return frc971::vision::CreateTargetPoseFbs(
113 *fbb, det.id, position_offset, orientation_offset, det.decision_margin);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800114}
115
milind-uf2a4e322023-02-01 19:33:10 -0800116void AprilRoboticsDetector::UndistortDetection(
117 apriltag_detection_t *det) const {
118 // 4 corners
119 constexpr size_t kRows = 4;
120 // 2d points
121 constexpr size_t kCols = 2;
122
123 cv::Mat distorted_points(kRows, kCols, CV_64F, det->p);
124 cv::Mat undistorted_points = cv::Mat::zeros(kRows, kCols, CV_64F);
125
126 // Undistort the april tag points
127 cv::undistortPoints(distorted_points, undistorted_points, intrinsics_,
128 dist_coeffs_, cv::noArray(), projection_matrix_);
129
130 // Copy the undistorted points into det
131 for (size_t i = 0; i < kRows; i++) {
132 for (size_t j = 0; j < kCols; j++) {
133 det->p[i][j] = undistorted_points.at<double>(i, j);
134 }
135 }
136}
137
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800138std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>>
milind-u7aa29e22023-02-23 20:22:01 -0800139AprilRoboticsDetector::DetectTags(cv::Mat image,
140 aos::monotonic_clock::time_point eof) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800141 const aos::monotonic_clock::time_point start_time =
142 aos::monotonic_clock::now();
143
144 image_u8_t im = {
milind-u09fb1252023-01-28 19:21:41 -0800145 .width = image.cols,
146 .height = image.rows,
147 .stride = image.cols,
148 .buf = image.data,
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800149 };
150
151 ftrace_.FormatMessage("Starting detect\n");
152 zarray_t *detections = apriltag_detector_detect(tag_detector_, &im);
153 ftrace_.FormatMessage("Done detecting\n");
154
155 std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>> results;
156
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
milind-ueccac3c2023-02-25 20:54:47 -0800182 UndistortDetection(det);
183
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800184 apriltag_pose_t pose;
185 double err = estimate_tag_pose(&info, &pose);
186
187 VLOG(1) << "err: " << err;
188
189 results.emplace_back(*det, pose);
190
191 const aos::monotonic_clock::time_point after_pose_estimation =
192 aos::monotonic_clock::now();
193
194 VLOG(1) << "Took "
Austin Schuhd2667932023-02-04 16:22:39 -0800195 << chrono::duration<double>(after_pose_estimation -
196 before_pose_estimation)
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800197 .count()
198 << " seconds for pose estimation";
Yash Chainani728ae222023-02-04 19:48:12 -0800199
milind-u7aa29e22023-02-23 20:22:01 -0800200 std::vector<cv::Point2f> corner_points;
Yash Chainani728ae222023-02-04 19:48:12 -0800201 corner_points.emplace_back(det->p[0][0], det->p[0][1]);
202 corner_points.emplace_back(det->p[1][0], det->p[1][1]);
203 corner_points.emplace_back(det->p[2][0], det->p[2][1]);
204 corner_points.emplace_back(det->p[3][0], det->p[3][1]);
205
milind-u7aa29e22023-02-23 20:22:01 -0800206 corners_vector.emplace_back(corner_points);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800207 }
208 }
209
milind-u7aa29e22023-02-23 20:22:01 -0800210 const auto annotations_offset =
211 frc971::vision::BuildAnnotations(eof, corners_vector, 5.0, builder.fbb());
212 builder.CheckOk(builder.Send(annotations_offset));
Yash Chainani728ae222023-02-04 19:48:12 -0800213
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800214 apriltag_detections_destroy(detections);
215
216 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
217
milind-uf3ab8ba2023-02-04 17:56:16 -0800218 if (FLAGS_debug) {
219 timeprofile_display(tag_detector_->tp);
220 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800221
Austin Schuhd2667932023-02-04 16:22:39 -0800222 VLOG(1) << "Took " << chrono::duration<double>(end_time - start_time).count()
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800223 << " seconds to detect overall";
224
225 return results;
226}
227
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800228} // namespace vision
229} // namespace y2023