blob: 3ad667188c3e9570a6961af2a2613966e071fde9 [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 Ostrowski437b1fb2023-02-26 10:12:01 -080011DEFINE_int32(pixel_border, 3,
12 "Size of image border within which to reject detected corners");
milind-uf2a4e322023-02-01 19:33:10 -080013
Maxwell Hendersonfebee252023-01-28 16:53:52 -080014namespace y2023 {
15namespace vision {
16
Austin Schuhd2667932023-02-04 16:22:39 -080017namespace chrono = std::chrono;
18
Maxwell Hendersonfebee252023-01-28 16:53:52 -080019AprilRoboticsDetector::AprilRoboticsDetector(aos::EventLoop *event_loop,
20 std::string_view channel_name)
James Kuszmauld67f6d22023-02-05 17:37:25 -080021 : calibration_data_(event_loop),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080022 ftrace_(),
Jim Ostrowski437b1fb2023-02-26 10:12:01 -080023 image_callback_(event_loop, channel_name,
24 [&](cv::Mat image_color_mat,
25 const aos::monotonic_clock::time_point eof) {
26 HandleImage(image_color_mat, eof);
27 },
28 chrono::milliseconds(5)),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080029 target_map_sender_(
Yash Chainani728ae222023-02-04 19:48:12 -080030 event_loop->MakeSender<frc971::vision::TargetMap>("/camera")),
milind-u7aa29e22023-02-23 20:22:01 -080031 image_annotations_sender_(
32 event_loop->MakeSender<foxglove::ImageAnnotations>("/camera")) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080033 tag_family_ = tag16h5_create();
34 tag_detector_ = apriltag_detector_create();
35
36 apriltag_detector_add_family_bits(tag_detector_, tag_family_, 1);
37 tag_detector_->nthreads = 6;
38 tag_detector_->wp = workerpool_create(tag_detector_->nthreads);
39 tag_detector_->qtp.min_white_black_diff = 5;
40 tag_detector_->debug = FLAGS_debug;
41
42 std::string hostname = aos::network::GetHostname();
43
44 // Check team string is valid
James Kuszmauld67f6d22023-02-05 17:37:25 -080045 calibration_ = FindCameraCalibration(
46 calibration_data_.constants(), event_loop->node()->name()->string_view());
milind-uf2a4e322023-02-01 19:33:10 -080047
48 extrinsics_ = CameraExtrinsics(calibration_);
49
Maxwell Hendersonfebee252023-01-28 16:53:52 -080050 intrinsics_ = CameraIntrinsics(calibration_);
milind-uf2a4e322023-02-01 19:33:10 -080051 // Create an undistort projection matrix using the intrinsics
52 projection_matrix_ = cv::Mat::zeros(3, 4, CV_64F);
53 intrinsics_.rowRange(0, 3).colRange(0, 3).copyTo(
54 projection_matrix_.rowRange(0, 3).colRange(0, 3));
55
56 dist_coeffs_ = CameraDistCoeffs(calibration_);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080057
58 image_callback_.set_format(frc971::vision::ImageCallback::Format::GRAYSCALE);
59}
60
61AprilRoboticsDetector::~AprilRoboticsDetector() {
62 apriltag_detector_destroy(tag_detector_);
63 free(tag_family_);
64}
65
66void AprilRoboticsDetector::SetWorkerpoolAffinities() {
67 for (int i = 0; i < tag_detector_->wp->nthreads; i++) {
68 cpu_set_t affinity;
69 CPU_ZERO(&affinity);
70 CPU_SET(i, &affinity);
71 pthread_setaffinity_np(tag_detector_->wp->threads[i], sizeof(affinity),
72 &affinity);
73 struct sched_param param;
74 param.sched_priority = 20;
75 int res = pthread_setschedparam(tag_detector_->wp->threads[i], SCHED_FIFO,
76 &param);
77 PCHECK(res == 0) << "Failed to set priority of threadpool threads";
78 }
79}
80
milind-uf2a4e322023-02-01 19:33:10 -080081void AprilRoboticsDetector::HandleImage(cv::Mat image_grayscale,
milind-u09fb1252023-01-28 19:21:41 -080082 aos::monotonic_clock::time_point eof) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080083 std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>> detections =
milind-u7aa29e22023-02-23 20:22:01 -080084 DetectTags(image_grayscale, eof);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080085
86 auto builder = target_map_sender_.MakeBuilder();
87 std::vector<flatbuffers::Offset<frc971::vision::TargetPoseFbs>> target_poses;
88 for (const auto &[detection, pose] : detections) {
milind-u681c4712023-02-23 21:22:50 -080089 target_poses.emplace_back(BuildTargetPose(pose, detection, builder.fbb()));
Maxwell Hendersonfebee252023-01-28 16:53:52 -080090 }
91 const auto target_poses_offset = builder.fbb()->CreateVector(target_poses);
92 auto target_map_builder = builder.MakeBuilder<frc971::vision::TargetMap>();
Maxwell Hendersonfebee252023-01-28 16:53:52 -080093 target_map_builder.add_target_poses(target_poses_offset);
milind-u09fb1252023-01-28 19:21:41 -080094 target_map_builder.add_monotonic_timestamp_ns(eof.time_since_epoch().count());
Maxwell Hendersonfebee252023-01-28 16:53:52 -080095 builder.CheckOk(builder.Send(target_map_builder.Finish()));
96}
97
98flatbuffers::Offset<frc971::vision::TargetPoseFbs>
milind-u681c4712023-02-23 21:22:50 -080099AprilRoboticsDetector::BuildTargetPose(const apriltag_pose_t &pose,
100 const apriltag_detection_t &det,
101 flatbuffers::FlatBufferBuilder *fbb) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800102 const auto T =
103 Eigen::Translation3d(pose.t->data[0], pose.t->data[1], pose.t->data[2]);
milind-u3f5f83c2023-01-29 15:23:51 -0800104 const auto position_offset =
105 frc971::vision::CreatePosition(*fbb, T.x(), T.y(), T.z());
106
milind-u633c4c02023-02-25 22:51:45 -0800107 // Aprilrobotics stores the rotation matrix in row-major order
108 const auto orientation = Eigen::Quaterniond(
109 Eigen::Matrix<double, 3, 3, Eigen::RowMajor>(pose.R->data));
milind-u3f5f83c2023-01-29 15:23:51 -0800110 const auto orientation_offset = frc971::vision::CreateQuaternion(
111 *fbb, orientation.w(), orientation.x(), orientation.y(), orientation.z());
112
milind-u681c4712023-02-23 21:22:50 -0800113 return frc971::vision::CreateTargetPoseFbs(
114 *fbb, det.id, position_offset, orientation_offset, det.decision_margin);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800115}
116
milind-uf2a4e322023-02-01 19:33:10 -0800117void AprilRoboticsDetector::UndistortDetection(
118 apriltag_detection_t *det) const {
119 // 4 corners
120 constexpr size_t kRows = 4;
121 // 2d points
122 constexpr size_t kCols = 2;
123
124 cv::Mat distorted_points(kRows, kCols, CV_64F, det->p);
125 cv::Mat undistorted_points = cv::Mat::zeros(kRows, kCols, CV_64F);
126
127 // Undistort the april tag points
128 cv::undistortPoints(distorted_points, undistorted_points, intrinsics_,
129 dist_coeffs_, cv::noArray(), projection_matrix_);
130
131 // Copy the undistorted points into det
132 for (size_t i = 0; i < kRows; i++) {
133 for (size_t j = 0; j < kCols; j++) {
134 det->p[i][j] = undistorted_points.at<double>(i, j);
135 }
136 }
137}
138
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800139std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>>
milind-u7aa29e22023-02-23 20:22:01 -0800140AprilRoboticsDetector::DetectTags(cv::Mat image,
141 aos::monotonic_clock::time_point eof) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800142 const aos::monotonic_clock::time_point start_time =
143 aos::monotonic_clock::now();
144
145 image_u8_t im = {
milind-u09fb1252023-01-28 19:21:41 -0800146 .width = image.cols,
147 .height = image.rows,
148 .stride = image.cols,
149 .buf = image.data,
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800150 };
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800151 const uint32_t min_x = FLAGS_pixel_border;
152 const uint32_t max_x = image.cols - FLAGS_pixel_border;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800153
154 ftrace_.FormatMessage("Starting detect\n");
155 zarray_t *detections = apriltag_detector_detect(tag_detector_, &im);
156 ftrace_.FormatMessage("Done detecting\n");
157
158 std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>> results;
159
milind-u7aa29e22023-02-23 20:22:01 -0800160 std::vector<std::vector<cv::Point2f>> corners_vector;
Yash Chainani728ae222023-02-04 19:48:12 -0800161
milind-u7aa29e22023-02-23 20:22:01 -0800162 auto builder = image_annotations_sender_.MakeBuilder();
Yash Chainani728ae222023-02-04 19:48:12 -0800163
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800164 for (int i = 0; i < zarray_size(detections); i++) {
165 apriltag_detection_t *det;
166 zarray_get(detections, i, &det);
167
milind-uf2a4e322023-02-01 19:33:10 -0800168 if (det->decision_margin > FLAGS_min_decision_margin) {
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800169 if (det->p[0][0] < min_x || det->p[0][0] > max_x ||
170 det->p[1][0] < min_x || det->p[1][0] > max_x ||
171 det->p[2][0] < min_x || det->p[2][0] > max_x ||
172 det->p[3][0] < min_x || det->p[3][0] > max_x) {
173 VLOG(1) << "Rejecting detection because corner is outside pixel border";
174 continue;
175 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800176 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
177 << " margin: " << det->decision_margin;
178
179 const aos::monotonic_clock::time_point before_pose_estimation =
180 aos::monotonic_clock::now();
181 // First create an apriltag_detection_info_t struct using your known
182 // parameters.
183 apriltag_detection_info_t info;
184 info.det = det;
185 info.tagsize = 0.1524;
milind-uf2a4e322023-02-01 19:33:10 -0800186
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800187 info.fx = intrinsics_.at<double>(0, 0);
188 info.fy = intrinsics_.at<double>(1, 1);
189 info.cx = intrinsics_.at<double>(0, 2);
190 info.cy = intrinsics_.at<double>(1, 2);
191
milind-ueccac3c2023-02-25 20:54:47 -0800192 UndistortDetection(det);
193
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800194 apriltag_pose_t pose;
195 double err = estimate_tag_pose(&info, &pose);
196
197 VLOG(1) << "err: " << err;
198
199 results.emplace_back(*det, pose);
200
201 const aos::monotonic_clock::time_point after_pose_estimation =
202 aos::monotonic_clock::now();
203
204 VLOG(1) << "Took "
Austin Schuhd2667932023-02-04 16:22:39 -0800205 << chrono::duration<double>(after_pose_estimation -
206 before_pose_estimation)
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800207 .count()
208 << " seconds for pose estimation";
Yash Chainani728ae222023-02-04 19:48:12 -0800209
milind-u7aa29e22023-02-23 20:22:01 -0800210 std::vector<cv::Point2f> corner_points;
Yash Chainani728ae222023-02-04 19:48:12 -0800211 corner_points.emplace_back(det->p[0][0], det->p[0][1]);
212 corner_points.emplace_back(det->p[1][0], det->p[1][1]);
213 corner_points.emplace_back(det->p[2][0], det->p[2][1]);
214 corner_points.emplace_back(det->p[3][0], det->p[3][1]);
215
milind-u7aa29e22023-02-23 20:22:01 -0800216 corners_vector.emplace_back(corner_points);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800217 }
218 }
219
milind-u7aa29e22023-02-23 20:22:01 -0800220 const auto annotations_offset =
221 frc971::vision::BuildAnnotations(eof, corners_vector, 5.0, builder.fbb());
222 builder.CheckOk(builder.Send(annotations_offset));
Yash Chainani728ae222023-02-04 19:48:12 -0800223
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800224 apriltag_detections_destroy(detections);
225
226 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
227
milind-uf3ab8ba2023-02-04 17:56:16 -0800228 if (FLAGS_debug) {
229 timeprofile_display(tag_detector_->tp);
230 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800231
Austin Schuhd2667932023-02-04 16:22:39 -0800232 VLOG(1) << "Took " << chrono::duration<double>(end_time - start_time).count()
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800233 << " seconds to detect overall";
234
235 return results;
236}
237
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800238} // namespace vision
239} // namespace y2023