blob: 315042f947df99ad45fdb618d999df23f93aa300 [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-uf2a4e322023-02-01 19:33:10 -08009DEFINE_double(min_decision_margin, 30.0,
10 "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
106 const auto orientation = Eigen::Quaterniond(Eigen::Matrix3d(pose.R->data));
107 const auto orientation_offset = frc971::vision::CreateQuaternion(
108 *fbb, orientation.w(), orientation.x(), orientation.y(), orientation.z());
109
milind-u681c4712023-02-23 21:22:50 -0800110 return frc971::vision::CreateTargetPoseFbs(
111 *fbb, det.id, position_offset, orientation_offset, det.decision_margin);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800112}
113
milind-uf2a4e322023-02-01 19:33:10 -0800114void AprilRoboticsDetector::UndistortDetection(
115 apriltag_detection_t *det) const {
116 // 4 corners
117 constexpr size_t kRows = 4;
118 // 2d points
119 constexpr size_t kCols = 2;
120
121 cv::Mat distorted_points(kRows, kCols, CV_64F, det->p);
122 cv::Mat undistorted_points = cv::Mat::zeros(kRows, kCols, CV_64F);
123
124 // Undistort the april tag points
125 cv::undistortPoints(distorted_points, undistorted_points, intrinsics_,
126 dist_coeffs_, cv::noArray(), projection_matrix_);
127
128 // Copy the undistorted points into det
129 for (size_t i = 0; i < kRows; i++) {
130 for (size_t j = 0; j < kCols; j++) {
131 det->p[i][j] = undistorted_points.at<double>(i, j);
132 }
133 }
134}
135
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800136std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>>
milind-u7aa29e22023-02-23 20:22:01 -0800137AprilRoboticsDetector::DetectTags(cv::Mat image,
138 aos::monotonic_clock::time_point eof) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800139 const aos::monotonic_clock::time_point start_time =
140 aos::monotonic_clock::now();
141
142 image_u8_t im = {
milind-u09fb1252023-01-28 19:21:41 -0800143 .width = image.cols,
144 .height = image.rows,
145 .stride = image.cols,
146 .buf = image.data,
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800147 };
148
149 ftrace_.FormatMessage("Starting detect\n");
150 zarray_t *detections = apriltag_detector_detect(tag_detector_, &im);
151 ftrace_.FormatMessage("Done detecting\n");
152
153 std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>> results;
154
milind-u7aa29e22023-02-23 20:22:01 -0800155 std::vector<std::vector<cv::Point2f>> corners_vector;
Yash Chainani728ae222023-02-04 19:48:12 -0800156
milind-u7aa29e22023-02-23 20:22:01 -0800157 auto builder = image_annotations_sender_.MakeBuilder();
Yash Chainani728ae222023-02-04 19:48:12 -0800158
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800159 for (int i = 0; i < zarray_size(detections); i++) {
160 apriltag_detection_t *det;
161 zarray_get(detections, i, &det);
162
milind-uf2a4e322023-02-01 19:33:10 -0800163 if (det->decision_margin > FLAGS_min_decision_margin) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800164 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
165 << " margin: " << det->decision_margin;
166
167 const aos::monotonic_clock::time_point before_pose_estimation =
168 aos::monotonic_clock::now();
169 // First create an apriltag_detection_info_t struct using your known
170 // parameters.
171 apriltag_detection_info_t info;
172 info.det = det;
173 info.tagsize = 0.1524;
milind-uf2a4e322023-02-01 19:33:10 -0800174
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800175 info.fx = intrinsics_.at<double>(0, 0);
176 info.fy = intrinsics_.at<double>(1, 1);
177 info.cx = intrinsics_.at<double>(0, 2);
178 info.cy = intrinsics_.at<double>(1, 2);
179
180 apriltag_pose_t pose;
181 double err = estimate_tag_pose(&info, &pose);
182
milind-uf2a4e322023-02-01 19:33:10 -0800183 UndistortDetection(det);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800184 VLOG(1) << "err: " << err;
185
186 results.emplace_back(*det, pose);
187
188 const aos::monotonic_clock::time_point after_pose_estimation =
189 aos::monotonic_clock::now();
190
191 VLOG(1) << "Took "
Austin Schuhd2667932023-02-04 16:22:39 -0800192 << chrono::duration<double>(after_pose_estimation -
193 before_pose_estimation)
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800194 .count()
195 << " seconds for pose estimation";
Yash Chainani728ae222023-02-04 19:48:12 -0800196
milind-u7aa29e22023-02-23 20:22:01 -0800197 std::vector<cv::Point2f> corner_points;
Yash Chainani728ae222023-02-04 19:48:12 -0800198 corner_points.emplace_back(det->p[0][0], det->p[0][1]);
199 corner_points.emplace_back(det->p[1][0], det->p[1][1]);
200 corner_points.emplace_back(det->p[2][0], det->p[2][1]);
201 corner_points.emplace_back(det->p[3][0], det->p[3][1]);
202
milind-u7aa29e22023-02-23 20:22:01 -0800203 corners_vector.emplace_back(corner_points);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800204 }
205 }
206
milind-u7aa29e22023-02-23 20:22:01 -0800207 const auto annotations_offset =
208 frc971::vision::BuildAnnotations(eof, corners_vector, 5.0, builder.fbb());
209 builder.CheckOk(builder.Send(annotations_offset));
Yash Chainani728ae222023-02-04 19:48:12 -0800210
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800211 apriltag_detections_destroy(detections);
212
213 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
214
milind-uf3ab8ba2023-02-04 17:56:16 -0800215 if (FLAGS_debug) {
216 timeprofile_display(tag_detector_->tp);
217 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800218
Austin Schuhd2667932023-02-04 16:22:39 -0800219 VLOG(1) << "Took " << chrono::duration<double>(end_time - start_time).count()
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800220 << " seconds to detect overall";
221
222 return results;
223}
224
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800225} // namespace vision
226} // namespace y2023