blob: ec743c553e588a5162628744c20dc24f1296610f [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 Ostrowski14124a32023-03-03 22:16:07 -080011DEFINE_int32(pixel_border, 10,
Jim Ostrowski437b1fb2023-02-26 10:12:01 -080012 "Size of image border within which to reject detected corners");
milind-u60e7fe52023-02-26 16:13:50 -080013DEFINE_double(
14 max_expected_distortion, 0.0005,
15 "Maximum expected value for unscaled distortion factors. Will scale "
16 "distortion factors so that this value (and a higher distortion) maps to "
17 "1.0.");
milind-uf2a4e322023-02-01 19:33:10 -080018
Maxwell Hendersonfebee252023-01-28 16:53:52 -080019namespace y2023 {
20namespace vision {
21
Austin Schuhd2667932023-02-04 16:22:39 -080022namespace chrono = std::chrono;
23
Maxwell Hendersonfebee252023-01-28 16:53:52 -080024AprilRoboticsDetector::AprilRoboticsDetector(aos::EventLoop *event_loop,
25 std::string_view channel_name)
James Kuszmauld67f6d22023-02-05 17:37:25 -080026 : calibration_data_(event_loop),
milind-uf5b3b4b2023-02-26 14:50:38 -080027 image_size_(0, 0),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080028 ftrace_(),
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -080029 image_callback_(event_loop, channel_name,
30 [&](cv::Mat image_color_mat,
31 const aos::monotonic_clock::time_point eof) {
32 HandleImage(image_color_mat, eof);
33 },
34 chrono::milliseconds(5)),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080035 target_map_sender_(
Yash Chainani728ae222023-02-04 19:48:12 -080036 event_loop->MakeSender<frc971::vision::TargetMap>("/camera")),
milind-u7aa29e22023-02-23 20:22:01 -080037 image_annotations_sender_(
38 event_loop->MakeSender<foxglove::ImageAnnotations>("/camera")) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080039 tag_family_ = tag16h5_create();
40 tag_detector_ = apriltag_detector_create();
41
42 apriltag_detector_add_family_bits(tag_detector_, tag_family_, 1);
43 tag_detector_->nthreads = 6;
44 tag_detector_->wp = workerpool_create(tag_detector_->nthreads);
45 tag_detector_->qtp.min_white_black_diff = 5;
46 tag_detector_->debug = FLAGS_debug;
47
48 std::string hostname = aos::network::GetHostname();
49
50 // Check team string is valid
James Kuszmauld67f6d22023-02-05 17:37:25 -080051 calibration_ = FindCameraCalibration(
52 calibration_data_.constants(), event_loop->node()->name()->string_view());
milind-uf2a4e322023-02-01 19:33:10 -080053
54 extrinsics_ = CameraExtrinsics(calibration_);
55
Maxwell Hendersonfebee252023-01-28 16:53:52 -080056 intrinsics_ = CameraIntrinsics(calibration_);
milind-uf2a4e322023-02-01 19:33:10 -080057 // Create an undistort projection matrix using the intrinsics
58 projection_matrix_ = cv::Mat::zeros(3, 4, CV_64F);
59 intrinsics_.rowRange(0, 3).colRange(0, 3).copyTo(
60 projection_matrix_.rowRange(0, 3).colRange(0, 3));
61
62 dist_coeffs_ = CameraDistCoeffs(calibration_);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080063
64 image_callback_.set_format(frc971::vision::ImageCallback::Format::GRAYSCALE);
65}
66
67AprilRoboticsDetector::~AprilRoboticsDetector() {
68 apriltag_detector_destroy(tag_detector_);
69 free(tag_family_);
70}
71
72void AprilRoboticsDetector::SetWorkerpoolAffinities() {
73 for (int i = 0; i < tag_detector_->wp->nthreads; i++) {
74 cpu_set_t affinity;
75 CPU_ZERO(&affinity);
76 CPU_SET(i, &affinity);
77 pthread_setaffinity_np(tag_detector_->wp->threads[i], sizeof(affinity),
78 &affinity);
79 struct sched_param param;
80 param.sched_priority = 20;
81 int res = pthread_setschedparam(tag_detector_->wp->threads[i], SCHED_FIFO,
82 &param);
83 PCHECK(res == 0) << "Failed to set priority of threadpool threads";
84 }
85}
86
milind-uf2a4e322023-02-01 19:33:10 -080087void AprilRoboticsDetector::HandleImage(cv::Mat image_grayscale,
milind-u09fb1252023-01-28 19:21:41 -080088 aos::monotonic_clock::time_point eof) {
milind-uf5b3b4b2023-02-26 14:50:38 -080089 image_size_ = image_grayscale.size();
90
milind-ufc8ab702023-02-26 14:14:39 -080091 std::vector<Detection> detections = DetectTags(image_grayscale, eof);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080092
93 auto builder = target_map_sender_.MakeBuilder();
94 std::vector<flatbuffers::Offset<frc971::vision::TargetPoseFbs>> target_poses;
milind-ufc8ab702023-02-26 14:14:39 -080095 for (const auto &detection : detections) {
96 target_poses.emplace_back(BuildTargetPose(detection, builder.fbb()));
Maxwell Hendersonfebee252023-01-28 16:53:52 -080097 }
98 const auto target_poses_offset = builder.fbb()->CreateVector(target_poses);
99 auto target_map_builder = builder.MakeBuilder<frc971::vision::TargetMap>();
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800100 target_map_builder.add_target_poses(target_poses_offset);
milind-u09fb1252023-01-28 19:21:41 -0800101 target_map_builder.add_monotonic_timestamp_ns(eof.time_since_epoch().count());
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800102 builder.CheckOk(builder.Send(target_map_builder.Finish()));
103}
104
105flatbuffers::Offset<frc971::vision::TargetPoseFbs>
milind-ufc8ab702023-02-26 14:14:39 -0800106AprilRoboticsDetector::BuildTargetPose(const Detection &detection,
milind-u681c4712023-02-23 21:22:50 -0800107 flatbuffers::FlatBufferBuilder *fbb) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800108 const auto T =
milind-ufc8ab702023-02-26 14:14:39 -0800109 Eigen::Translation3d(detection.pose.t->data[0], detection.pose.t->data[1],
110 detection.pose.t->data[2]);
milind-u3f5f83c2023-01-29 15:23:51 -0800111 const auto position_offset =
112 frc971::vision::CreatePosition(*fbb, T.x(), T.y(), T.z());
113
milind-u633c4c02023-02-25 22:51:45 -0800114 // Aprilrobotics stores the rotation matrix in row-major order
115 const auto orientation = Eigen::Quaterniond(
milind-ufc8ab702023-02-26 14:14:39 -0800116 Eigen::Matrix<double, 3, 3, Eigen::RowMajor>(detection.pose.R->data));
milind-u3f5f83c2023-01-29 15:23:51 -0800117 const auto orientation_offset = frc971::vision::CreateQuaternion(
118 *fbb, orientation.w(), orientation.x(), orientation.y(), orientation.z());
119
milind-u681c4712023-02-23 21:22:50 -0800120 return frc971::vision::CreateTargetPoseFbs(
milind-ufc8ab702023-02-26 14:14:39 -0800121 *fbb, detection.det.id, position_offset, orientation_offset,
milind-uf5b3b4b2023-02-26 14:50:38 -0800122 detection.det.decision_margin, detection.pose_error,
123 detection.distortion_factor);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800124}
125
milind-uf2a4e322023-02-01 19:33:10 -0800126void AprilRoboticsDetector::UndistortDetection(
127 apriltag_detection_t *det) const {
128 // 4 corners
129 constexpr size_t kRows = 4;
130 // 2d points
131 constexpr size_t kCols = 2;
132
133 cv::Mat distorted_points(kRows, kCols, CV_64F, det->p);
134 cv::Mat undistorted_points = cv::Mat::zeros(kRows, kCols, CV_64F);
135
136 // Undistort the april tag points
137 cv::undistortPoints(distorted_points, undistorted_points, intrinsics_,
138 dist_coeffs_, cv::noArray(), projection_matrix_);
139
140 // Copy the undistorted points into det
141 for (size_t i = 0; i < kRows; i++) {
142 for (size_t j = 0; j < kCols; j++) {
143 det->p[i][j] = undistorted_points.at<double>(i, j);
144 }
145 }
146}
147
milind-uf5b3b4b2023-02-26 14:50:38 -0800148double AprilRoboticsDetector::ComputeDistortionFactor(
149 const std::vector<cv::Point2f> &orig_corners,
150 const std::vector<cv::Point2f> &corners) {
151 CHECK_EQ(orig_corners.size(), 4ul);
152 CHECK_EQ(corners.size(), 4ul);
153
154 double avg_distance = 0.0;
155 for (size_t i = 0; i < corners.size(); i++) {
156 avg_distance += cv::norm(orig_corners[i] - corners[i]);
157 }
158 avg_distance /= corners.size();
159
milind-u60e7fe52023-02-26 16:13:50 -0800160 // Normalize avg_distance by dividing by the image size, and then the maximum
161 // expected distortion
milind-uf5b3b4b2023-02-26 14:50:38 -0800162 double distortion_factor =
163 avg_distance /
164 static_cast<double>(image_size_.width * image_size_.height);
milind-u60e7fe52023-02-26 16:13:50 -0800165 return std::min(distortion_factor / FLAGS_max_expected_distortion, 1.0);
milind-uf5b3b4b2023-02-26 14:50:38 -0800166}
167
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800168std::vector<cv::Point2f> AprilRoboticsDetector::MakeCornerVector(
169 const apriltag_detection_t *det) {
170 std::vector<cv::Point2f> corner_points;
171 corner_points.emplace_back(det->p[0][0], det->p[0][1]);
172 corner_points.emplace_back(det->p[1][0], det->p[1][1]);
173 corner_points.emplace_back(det->p[2][0], det->p[2][1]);
174 corner_points.emplace_back(det->p[3][0], det->p[3][1]);
175
176 return corner_points;
177}
178
milind-ufc8ab702023-02-26 14:14:39 -0800179std::vector<AprilRoboticsDetector::Detection> AprilRoboticsDetector::DetectTags(
180 cv::Mat image, aos::monotonic_clock::time_point eof) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800181 const aos::monotonic_clock::time_point start_time =
182 aos::monotonic_clock::now();
183
184 image_u8_t im = {
milind-u09fb1252023-01-28 19:21:41 -0800185 .width = image.cols,
186 .height = image.rows,
187 .stride = image.cols,
188 .buf = image.data,
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800189 };
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800190 const uint32_t min_x = FLAGS_pixel_border;
191 const uint32_t max_x = image.cols - FLAGS_pixel_border;
Jim Ostrowski0197d6b2023-03-04 12:41:13 -0800192 const uint32_t min_y = FLAGS_pixel_border;
193 const uint32_t max_y = image.rows - FLAGS_pixel_border;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800194
195 ftrace_.FormatMessage("Starting detect\n");
196 zarray_t *detections = apriltag_detector_detect(tag_detector_, &im);
197 ftrace_.FormatMessage("Done detecting\n");
198
milind-ufc8ab702023-02-26 14:14:39 -0800199 std::vector<Detection> results;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800200
milind-u7aa29e22023-02-23 20:22:01 -0800201 auto builder = image_annotations_sender_.MakeBuilder();
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800202 std::vector<flatbuffers::Offset<foxglove::PointsAnnotation>> foxglove_corners;
Yash Chainani728ae222023-02-04 19:48:12 -0800203
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800204 for (int i = 0; i < zarray_size(detections); i++) {
205 apriltag_detection_t *det;
206 zarray_get(detections, i, &det);
207
milind-uf2a4e322023-02-01 19:33:10 -0800208 if (det->decision_margin > FLAGS_min_decision_margin) {
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800209 if (det->p[0][0] < min_x || det->p[0][0] > max_x ||
210 det->p[1][0] < min_x || det->p[1][0] > max_x ||
211 det->p[2][0] < min_x || det->p[2][0] > max_x ||
Jim Ostrowski0197d6b2023-03-04 12:41:13 -0800212 det->p[3][0] < min_x || det->p[3][0] > max_x ||
213 det->p[0][1] < min_y || det->p[0][1] > max_y ||
214 det->p[1][1] < min_y || det->p[1][1] > max_y ||
215 det->p[2][1] < min_y || det->p[2][1] > max_y ||
216 det->p[3][1] < min_y || det->p[3][1] > max_y) {
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800217 VLOG(1) << "Rejecting detection because corner is outside pixel border";
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800218 // Send rejected corner points in red
219 std::vector<cv::Point2f> rejected_corner_points = MakeCornerVector(det);
220 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
221 builder.fbb(), eof, rejected_corner_points,
222 std::vector<double>{1.0, 0.0, 0.0, 0.5}));
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800223 continue;
224 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800225 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
226 << " margin: " << det->decision_margin;
227
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800228 // First create an apriltag_detection_info_t struct using your known
229 // parameters.
230 apriltag_detection_info_t info;
231 info.det = det;
232 info.tagsize = 0.1524;
milind-uf2a4e322023-02-01 19:33:10 -0800233
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800234 info.fx = intrinsics_.at<double>(0, 0);
235 info.fy = intrinsics_.at<double>(1, 1);
236 info.cx = intrinsics_.at<double>(0, 2);
237 info.cy = intrinsics_.at<double>(1, 2);
238
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800239 // Send original corner points in green
240 std::vector<cv::Point2f> orig_corner_points = MakeCornerVector(det);
241 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
242 builder.fbb(), eof, orig_corner_points,
243 std::vector<double>{0.0, 1.0, 0.0, 0.5}));
Jim Ostrowskid2b5c912023-02-26 00:59:35 -0800244
milind-ueccac3c2023-02-25 20:54:47 -0800245 UndistortDetection(det);
246
milind-uf5b3b4b2023-02-26 14:50:38 -0800247 const aos::monotonic_clock::time_point before_pose_estimation =
248 aos::monotonic_clock::now();
249
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800250 apriltag_pose_t pose;
milind-uf5b3b4b2023-02-26 14:50:38 -0800251 double pose_error = estimate_tag_pose(&info, &pose);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800252
253 const aos::monotonic_clock::time_point after_pose_estimation =
254 aos::monotonic_clock::now();
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800255 VLOG(1) << "Took "
Austin Schuhd2667932023-02-04 16:22:39 -0800256 << chrono::duration<double>(after_pose_estimation -
257 before_pose_estimation)
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800258 .count()
259 << " seconds for pose estimation";
milind-uf5b3b4b2023-02-26 14:50:38 -0800260 VLOG(1) << "Pose err: " << pose_error;
Yash Chainani728ae222023-02-04 19:48:12 -0800261
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800262 // Send undistorted corner points in pink
263 std::vector<cv::Point2f> corner_points = MakeCornerVector(det);
264 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
265 builder.fbb(), eof, corner_points,
266 std::vector<double>{1.0, 0.75, 0.8, 1.0}));
milind-uf5b3b4b2023-02-26 14:50:38 -0800267
268 double distortion_factor =
269 ComputeDistortionFactor(orig_corner_points, corner_points);
270
271 results.emplace_back(Detection{.det = *det,
272 .pose = pose,
273 .pose_error = pose_error,
274 .distortion_factor = distortion_factor});
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800275 }
276 }
277
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800278 foxglove::ImageAnnotations::Builder annotation_builder(*builder.fbb());
279 const auto corners_offset = builder.fbb()->CreateVector(foxglove_corners);
280 annotation_builder.add_points(corners_offset);
281 builder.CheckOk(builder.Send(annotation_builder.Finish()));
Yash Chainani728ae222023-02-04 19:48:12 -0800282
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800283 apriltag_detections_destroy(detections);
284
285 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
286
milind-uf3ab8ba2023-02-04 17:56:16 -0800287 if (FLAGS_debug) {
288 timeprofile_display(tag_detector_->tp);
289 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800290
Austin Schuhd2667932023-02-04 16:22:39 -0800291 VLOG(1) << "Took " << chrono::duration<double>(end_time - start_time).count()
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800292 << " seconds to detect overall";
293
294 return results;
295}
296
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800297} // namespace vision
298} // namespace y2023