blob: e694b5e3fb16232e314f095251da3bea6d05fce0 [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),
milind-uf5b3b4b2023-02-26 14:50:38 -080022 image_size_(0, 0),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080023 ftrace_(),
milind-ufc8ab702023-02-26 14:14:39 -080024 image_callback_(
25 event_loop, channel_name,
26 [&](cv::Mat image_color_mat,
27 const aos::monotonic_clock::time_point eof) {
28 HandleImage(image_color_mat, eof);
29 },
30 chrono::milliseconds(5)),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080031 target_map_sender_(
Yash Chainani728ae222023-02-04 19:48:12 -080032 event_loop->MakeSender<frc971::vision::TargetMap>("/camera")),
milind-u7aa29e22023-02-23 20:22:01 -080033 image_annotations_sender_(
34 event_loop->MakeSender<foxglove::ImageAnnotations>("/camera")) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080035 tag_family_ = tag16h5_create();
36 tag_detector_ = apriltag_detector_create();
37
38 apriltag_detector_add_family_bits(tag_detector_, tag_family_, 1);
39 tag_detector_->nthreads = 6;
40 tag_detector_->wp = workerpool_create(tag_detector_->nthreads);
41 tag_detector_->qtp.min_white_black_diff = 5;
42 tag_detector_->debug = FLAGS_debug;
43
44 std::string hostname = aos::network::GetHostname();
45
46 // Check team string is valid
James Kuszmauld67f6d22023-02-05 17:37:25 -080047 calibration_ = FindCameraCalibration(
48 calibration_data_.constants(), event_loop->node()->name()->string_view());
milind-uf2a4e322023-02-01 19:33:10 -080049
50 extrinsics_ = CameraExtrinsics(calibration_);
51
Maxwell Hendersonfebee252023-01-28 16:53:52 -080052 intrinsics_ = CameraIntrinsics(calibration_);
milind-uf2a4e322023-02-01 19:33:10 -080053 // Create an undistort projection matrix using the intrinsics
54 projection_matrix_ = cv::Mat::zeros(3, 4, CV_64F);
55 intrinsics_.rowRange(0, 3).colRange(0, 3).copyTo(
56 projection_matrix_.rowRange(0, 3).colRange(0, 3));
57
58 dist_coeffs_ = CameraDistCoeffs(calibration_);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080059
60 image_callback_.set_format(frc971::vision::ImageCallback::Format::GRAYSCALE);
61}
62
63AprilRoboticsDetector::~AprilRoboticsDetector() {
64 apriltag_detector_destroy(tag_detector_);
65 free(tag_family_);
66}
67
68void AprilRoboticsDetector::SetWorkerpoolAffinities() {
69 for (int i = 0; i < tag_detector_->wp->nthreads; i++) {
70 cpu_set_t affinity;
71 CPU_ZERO(&affinity);
72 CPU_SET(i, &affinity);
73 pthread_setaffinity_np(tag_detector_->wp->threads[i], sizeof(affinity),
74 &affinity);
75 struct sched_param param;
76 param.sched_priority = 20;
77 int res = pthread_setschedparam(tag_detector_->wp->threads[i], SCHED_FIFO,
78 &param);
79 PCHECK(res == 0) << "Failed to set priority of threadpool threads";
80 }
81}
82
milind-uf2a4e322023-02-01 19:33:10 -080083void AprilRoboticsDetector::HandleImage(cv::Mat image_grayscale,
milind-u09fb1252023-01-28 19:21:41 -080084 aos::monotonic_clock::time_point eof) {
milind-uf5b3b4b2023-02-26 14:50:38 -080085 image_size_ = image_grayscale.size();
86
milind-ufc8ab702023-02-26 14:14:39 -080087 std::vector<Detection> detections = DetectTags(image_grayscale, eof);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080088
89 auto builder = target_map_sender_.MakeBuilder();
90 std::vector<flatbuffers::Offset<frc971::vision::TargetPoseFbs>> target_poses;
milind-ufc8ab702023-02-26 14:14:39 -080091 for (const auto &detection : detections) {
92 target_poses.emplace_back(BuildTargetPose(detection, builder.fbb()));
Maxwell Hendersonfebee252023-01-28 16:53:52 -080093 }
94 const auto target_poses_offset = builder.fbb()->CreateVector(target_poses);
95 auto target_map_builder = builder.MakeBuilder<frc971::vision::TargetMap>();
Maxwell Hendersonfebee252023-01-28 16:53:52 -080096 target_map_builder.add_target_poses(target_poses_offset);
milind-u09fb1252023-01-28 19:21:41 -080097 target_map_builder.add_monotonic_timestamp_ns(eof.time_since_epoch().count());
Maxwell Hendersonfebee252023-01-28 16:53:52 -080098 builder.CheckOk(builder.Send(target_map_builder.Finish()));
99}
100
101flatbuffers::Offset<frc971::vision::TargetPoseFbs>
milind-ufc8ab702023-02-26 14:14:39 -0800102AprilRoboticsDetector::BuildTargetPose(const Detection &detection,
milind-u681c4712023-02-23 21:22:50 -0800103 flatbuffers::FlatBufferBuilder *fbb) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800104 const auto T =
milind-ufc8ab702023-02-26 14:14:39 -0800105 Eigen::Translation3d(detection.pose.t->data[0], detection.pose.t->data[1],
106 detection.pose.t->data[2]);
milind-u3f5f83c2023-01-29 15:23:51 -0800107 const auto position_offset =
108 frc971::vision::CreatePosition(*fbb, T.x(), T.y(), T.z());
109
milind-u633c4c02023-02-25 22:51:45 -0800110 // Aprilrobotics stores the rotation matrix in row-major order
111 const auto orientation = Eigen::Quaterniond(
milind-ufc8ab702023-02-26 14:14:39 -0800112 Eigen::Matrix<double, 3, 3, Eigen::RowMajor>(detection.pose.R->data));
milind-u3f5f83c2023-01-29 15:23:51 -0800113 const auto orientation_offset = frc971::vision::CreateQuaternion(
114 *fbb, orientation.w(), orientation.x(), orientation.y(), orientation.z());
115
milind-u681c4712023-02-23 21:22:50 -0800116 return frc971::vision::CreateTargetPoseFbs(
milind-ufc8ab702023-02-26 14:14:39 -0800117 *fbb, detection.det.id, position_offset, orientation_offset,
milind-uf5b3b4b2023-02-26 14:50:38 -0800118 detection.det.decision_margin, detection.pose_error,
119 detection.distortion_factor);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800120}
121
milind-uf2a4e322023-02-01 19:33:10 -0800122void AprilRoboticsDetector::UndistortDetection(
123 apriltag_detection_t *det) const {
124 // 4 corners
125 constexpr size_t kRows = 4;
126 // 2d points
127 constexpr size_t kCols = 2;
128
129 cv::Mat distorted_points(kRows, kCols, CV_64F, det->p);
130 cv::Mat undistorted_points = cv::Mat::zeros(kRows, kCols, CV_64F);
131
132 // Undistort the april tag points
133 cv::undistortPoints(distorted_points, undistorted_points, intrinsics_,
134 dist_coeffs_, cv::noArray(), projection_matrix_);
135
136 // Copy the undistorted points into det
137 for (size_t i = 0; i < kRows; i++) {
138 for (size_t j = 0; j < kCols; j++) {
139 det->p[i][j] = undistorted_points.at<double>(i, j);
140 }
141 }
142}
143
milind-uf5b3b4b2023-02-26 14:50:38 -0800144double AprilRoboticsDetector::ComputeDistortionFactor(
145 const std::vector<cv::Point2f> &orig_corners,
146 const std::vector<cv::Point2f> &corners) {
147 CHECK_EQ(orig_corners.size(), 4ul);
148 CHECK_EQ(corners.size(), 4ul);
149
150 double avg_distance = 0.0;
151 for (size_t i = 0; i < corners.size(); i++) {
152 avg_distance += cv::norm(orig_corners[i] - corners[i]);
153 }
154 avg_distance /= corners.size();
155
156 // Normalize avg_distance by dividing by the image size
157 double distortion_factor =
158 avg_distance /
159 static_cast<double>(image_size_.width * image_size_.height);
160 return distortion_factor;
161}
162
milind-ufc8ab702023-02-26 14:14:39 -0800163std::vector<AprilRoboticsDetector::Detection> AprilRoboticsDetector::DetectTags(
164 cv::Mat image, aos::monotonic_clock::time_point eof) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800165 const aos::monotonic_clock::time_point start_time =
166 aos::monotonic_clock::now();
167
168 image_u8_t im = {
milind-u09fb1252023-01-28 19:21:41 -0800169 .width = image.cols,
170 .height = image.rows,
171 .stride = image.cols,
172 .buf = image.data,
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800173 };
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800174 const uint32_t min_x = FLAGS_pixel_border;
175 const uint32_t max_x = image.cols - FLAGS_pixel_border;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800176
177 ftrace_.FormatMessage("Starting detect\n");
178 zarray_t *detections = apriltag_detector_detect(tag_detector_, &im);
179 ftrace_.FormatMessage("Done detecting\n");
180
milind-ufc8ab702023-02-26 14:14:39 -0800181 std::vector<Detection> results;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800182
Jim Ostrowskid2b5c912023-02-26 00:59:35 -0800183 std::vector<std::vector<cv::Point2f>> orig_corners_vector;
milind-u7aa29e22023-02-23 20:22:01 -0800184 std::vector<std::vector<cv::Point2f>> corners_vector;
Yash Chainani728ae222023-02-04 19:48:12 -0800185
milind-u7aa29e22023-02-23 20:22:01 -0800186 auto builder = image_annotations_sender_.MakeBuilder();
Yash Chainani728ae222023-02-04 19:48:12 -0800187
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800188 for (int i = 0; i < zarray_size(detections); i++) {
189 apriltag_detection_t *det;
190 zarray_get(detections, i, &det);
191
milind-uf2a4e322023-02-01 19:33:10 -0800192 if (det->decision_margin > FLAGS_min_decision_margin) {
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800193 if (det->p[0][0] < min_x || det->p[0][0] > max_x ||
194 det->p[1][0] < min_x || det->p[1][0] > max_x ||
195 det->p[2][0] < min_x || det->p[2][0] > max_x ||
196 det->p[3][0] < min_x || det->p[3][0] > max_x) {
197 VLOG(1) << "Rejecting detection because corner is outside pixel border";
198 continue;
199 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800200 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
201 << " margin: " << det->decision_margin;
202
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800203 // First create an apriltag_detection_info_t struct using your known
204 // parameters.
205 apriltag_detection_info_t info;
206 info.det = det;
207 info.tagsize = 0.1524;
milind-uf2a4e322023-02-01 19:33:10 -0800208
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800209 info.fx = intrinsics_.at<double>(0, 0);
210 info.fy = intrinsics_.at<double>(1, 1);
211 info.cx = intrinsics_.at<double>(0, 2);
212 info.cy = intrinsics_.at<double>(1, 2);
213
Jim Ostrowskid2b5c912023-02-26 00:59:35 -0800214 // Store out the original, pre-undistortion corner points for sending
215 std::vector<cv::Point2f> orig_corner_points;
216 orig_corner_points.emplace_back(det->p[0][0], det->p[0][1]);
217 orig_corner_points.emplace_back(det->p[1][0], det->p[1][1]);
218 orig_corner_points.emplace_back(det->p[2][0], det->p[2][1]);
219 orig_corner_points.emplace_back(det->p[3][0], det->p[3][1]);
220
221 orig_corners_vector.emplace_back(orig_corner_points);
222
milind-ueccac3c2023-02-25 20:54:47 -0800223 UndistortDetection(det);
224
milind-uf5b3b4b2023-02-26 14:50:38 -0800225 const aos::monotonic_clock::time_point before_pose_estimation =
226 aos::monotonic_clock::now();
227
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800228 apriltag_pose_t pose;
milind-uf5b3b4b2023-02-26 14:50:38 -0800229 double pose_error = estimate_tag_pose(&info, &pose);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800230
231 const aos::monotonic_clock::time_point after_pose_estimation =
232 aos::monotonic_clock::now();
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800233 VLOG(1) << "Took "
Austin Schuhd2667932023-02-04 16:22:39 -0800234 << chrono::duration<double>(after_pose_estimation -
235 before_pose_estimation)
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800236 .count()
237 << " seconds for pose estimation";
milind-uf5b3b4b2023-02-26 14:50:38 -0800238 VLOG(1) << "Pose err: " << pose_error;
Yash Chainani728ae222023-02-04 19:48:12 -0800239
milind-u7aa29e22023-02-23 20:22:01 -0800240 std::vector<cv::Point2f> corner_points;
Yash Chainani728ae222023-02-04 19:48:12 -0800241 corner_points.emplace_back(det->p[0][0], det->p[0][1]);
242 corner_points.emplace_back(det->p[1][0], det->p[1][1]);
243 corner_points.emplace_back(det->p[2][0], det->p[2][1]);
244 corner_points.emplace_back(det->p[3][0], det->p[3][1]);
245
milind-u7aa29e22023-02-23 20:22:01 -0800246 corners_vector.emplace_back(corner_points);
milind-uf5b3b4b2023-02-26 14:50:38 -0800247
248 double distortion_factor =
249 ComputeDistortionFactor(orig_corner_points, corner_points);
250
251 results.emplace_back(Detection{.det = *det,
252 .pose = pose,
253 .pose_error = pose_error,
254 .distortion_factor = distortion_factor});
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800255 }
256 }
257
Jim Ostrowskid2b5c912023-02-26 00:59:35 -0800258 const auto annotations_offset = frc971::vision::BuildAnnotations(
259 eof, orig_corners_vector, 5.0, builder.fbb());
milind-u7aa29e22023-02-23 20:22:01 -0800260 builder.CheckOk(builder.Send(annotations_offset));
Yash Chainani728ae222023-02-04 19:48:12 -0800261
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800262 apriltag_detections_destroy(detections);
263
264 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
265
milind-uf3ab8ba2023-02-04 17:56:16 -0800266 if (FLAGS_debug) {
267 timeprofile_display(tag_detector_->tp);
268 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800269
Austin Schuhd2667932023-02-04 16:22:39 -0800270 VLOG(1) << "Took " << chrono::duration<double>(end_time - start_time).count()
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800271 << " seconds to detect overall";
272
273 return results;
274}
275
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800276} // namespace vision
277} // namespace y2023