blob: 317720c466470486bf3e78b4f4cbd6baad70b2fe [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
Jim Ostrowskid03f9892023-03-25 11:57:54 -07009DEFINE_double(min_decision_margin, 50.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(
milind-u8773c232023-03-11 14:59:06 -080014 max_expected_distortion, 0.314,
milind-u60e7fe52023-02-26 16:13:50 -080015 "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 Ostrowskid03f9892023-03-25 11:57:54 -070029 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_(
milind-u99b1a762023-03-12 16:48:32 -070038 event_loop->MakeSender<foxglove::ImageAnnotations>("/camera")),
39 rejections_(0) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080040 tag_family_ = tag16h5_create();
41 tag_detector_ = apriltag_detector_create();
42
43 apriltag_detector_add_family_bits(tag_detector_, tag_family_, 1);
44 tag_detector_->nthreads = 6;
45 tag_detector_->wp = workerpool_create(tag_detector_->nthreads);
46 tag_detector_->qtp.min_white_black_diff = 5;
47 tag_detector_->debug = FLAGS_debug;
48
49 std::string hostname = aos::network::GetHostname();
50
51 // Check team string is valid
James Kuszmauld67f6d22023-02-05 17:37:25 -080052 calibration_ = FindCameraCalibration(
53 calibration_data_.constants(), event_loop->node()->name()->string_view());
milind-uf2a4e322023-02-01 19:33:10 -080054
55 extrinsics_ = CameraExtrinsics(calibration_);
56
Maxwell Hendersonfebee252023-01-28 16:53:52 -080057 intrinsics_ = CameraIntrinsics(calibration_);
milind-uf2a4e322023-02-01 19:33:10 -080058 // Create an undistort projection matrix using the intrinsics
59 projection_matrix_ = cv::Mat::zeros(3, 4, CV_64F);
60 intrinsics_.rowRange(0, 3).colRange(0, 3).copyTo(
61 projection_matrix_.rowRange(0, 3).colRange(0, 3));
62
63 dist_coeffs_ = CameraDistCoeffs(calibration_);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080064
65 image_callback_.set_format(frc971::vision::ImageCallback::Format::GRAYSCALE);
66}
67
68AprilRoboticsDetector::~AprilRoboticsDetector() {
69 apriltag_detector_destroy(tag_detector_);
70 free(tag_family_);
71}
72
73void AprilRoboticsDetector::SetWorkerpoolAffinities() {
74 for (int i = 0; i < tag_detector_->wp->nthreads; i++) {
75 cpu_set_t affinity;
76 CPU_ZERO(&affinity);
77 CPU_SET(i, &affinity);
78 pthread_setaffinity_np(tag_detector_->wp->threads[i], sizeof(affinity),
79 &affinity);
80 struct sched_param param;
81 param.sched_priority = 20;
82 int res = pthread_setschedparam(tag_detector_->wp->threads[i], SCHED_FIFO,
83 &param);
84 PCHECK(res == 0) << "Failed to set priority of threadpool threads";
85 }
86}
87
milind-uf2a4e322023-02-01 19:33:10 -080088void AprilRoboticsDetector::HandleImage(cv::Mat image_grayscale,
milind-u09fb1252023-01-28 19:21:41 -080089 aos::monotonic_clock::time_point eof) {
milind-uf5b3b4b2023-02-26 14:50:38 -080090 image_size_ = image_grayscale.size();
91
milind-u99b1a762023-03-12 16:48:32 -070092 DetectionResult result = DetectTags(image_grayscale, eof);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080093
94 auto builder = target_map_sender_.MakeBuilder();
95 std::vector<flatbuffers::Offset<frc971::vision::TargetPoseFbs>> target_poses;
milind-u99b1a762023-03-12 16:48:32 -070096 for (const auto &detection : result.detections) {
milind-ufc8ab702023-02-26 14:14:39 -080097 target_poses.emplace_back(BuildTargetPose(detection, builder.fbb()));
Maxwell Hendersonfebee252023-01-28 16:53:52 -080098 }
99 const auto target_poses_offset = builder.fbb()->CreateVector(target_poses);
100 auto target_map_builder = builder.MakeBuilder<frc971::vision::TargetMap>();
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800101 target_map_builder.add_target_poses(target_poses_offset);
milind-u09fb1252023-01-28 19:21:41 -0800102 target_map_builder.add_monotonic_timestamp_ns(eof.time_since_epoch().count());
milind-u99b1a762023-03-12 16:48:32 -0700103 target_map_builder.add_rejections(result.rejections);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800104 builder.CheckOk(builder.Send(target_map_builder.Finish()));
105}
106
107flatbuffers::Offset<frc971::vision::TargetPoseFbs>
milind-ufc8ab702023-02-26 14:14:39 -0800108AprilRoboticsDetector::BuildTargetPose(const Detection &detection,
milind-u681c4712023-02-23 21:22:50 -0800109 flatbuffers::FlatBufferBuilder *fbb) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800110 const auto T =
milind-ufc8ab702023-02-26 14:14:39 -0800111 Eigen::Translation3d(detection.pose.t->data[0], detection.pose.t->data[1],
112 detection.pose.t->data[2]);
milind-u3f5f83c2023-01-29 15:23:51 -0800113 const auto position_offset =
114 frc971::vision::CreatePosition(*fbb, T.x(), T.y(), T.z());
115
milind-u633c4c02023-02-25 22:51:45 -0800116 // Aprilrobotics stores the rotation matrix in row-major order
117 const auto orientation = Eigen::Quaterniond(
milind-ufc8ab702023-02-26 14:14:39 -0800118 Eigen::Matrix<double, 3, 3, Eigen::RowMajor>(detection.pose.R->data));
milind-u3f5f83c2023-01-29 15:23:51 -0800119 const auto orientation_offset = frc971::vision::CreateQuaternion(
120 *fbb, orientation.w(), orientation.x(), orientation.y(), orientation.z());
121
milind-u681c4712023-02-23 21:22:50 -0800122 return frc971::vision::CreateTargetPoseFbs(
milind-ufc8ab702023-02-26 14:14:39 -0800123 *fbb, detection.det.id, position_offset, orientation_offset,
milind-uf5b3b4b2023-02-26 14:50:38 -0800124 detection.det.decision_margin, detection.pose_error,
125 detection.distortion_factor);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800126}
127
milind-uf2a4e322023-02-01 19:33:10 -0800128void AprilRoboticsDetector::UndistortDetection(
129 apriltag_detection_t *det) const {
130 // 4 corners
131 constexpr size_t kRows = 4;
132 // 2d points
133 constexpr size_t kCols = 2;
134
135 cv::Mat distorted_points(kRows, kCols, CV_64F, det->p);
136 cv::Mat undistorted_points = cv::Mat::zeros(kRows, kCols, CV_64F);
137
138 // Undistort the april tag points
139 cv::undistortPoints(distorted_points, undistorted_points, intrinsics_,
140 dist_coeffs_, cv::noArray(), projection_matrix_);
141
142 // Copy the undistorted points into det
143 for (size_t i = 0; i < kRows; i++) {
144 for (size_t j = 0; j < kCols; j++) {
145 det->p[i][j] = undistorted_points.at<double>(i, j);
146 }
147 }
148}
149
milind-uf5b3b4b2023-02-26 14:50:38 -0800150double AprilRoboticsDetector::ComputeDistortionFactor(
151 const std::vector<cv::Point2f> &orig_corners,
152 const std::vector<cv::Point2f> &corners) {
153 CHECK_EQ(orig_corners.size(), 4ul);
154 CHECK_EQ(corners.size(), 4ul);
155
156 double avg_distance = 0.0;
157 for (size_t i = 0; i < corners.size(); i++) {
158 avg_distance += cv::norm(orig_corners[i] - corners[i]);
159 }
160 avg_distance /= corners.size();
161
milind-u8773c232023-03-11 14:59:06 -0800162 // Normalize avg_distance by dividing by the image diagonal,
163 // and then the maximum expected distortion
milind-uf5b3b4b2023-02-26 14:50:38 -0800164 double distortion_factor =
165 avg_distance /
milind-u8773c232023-03-11 14:59:06 -0800166 cv::norm(cv::Point2d(image_size_.width, image_size_.height));
milind-u60e7fe52023-02-26 16:13:50 -0800167 return std::min(distortion_factor / FLAGS_max_expected_distortion, 1.0);
milind-uf5b3b4b2023-02-26 14:50:38 -0800168}
169
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800170std::vector<cv::Point2f> AprilRoboticsDetector::MakeCornerVector(
171 const apriltag_detection_t *det) {
172 std::vector<cv::Point2f> corner_points;
173 corner_points.emplace_back(det->p[0][0], det->p[0][1]);
174 corner_points.emplace_back(det->p[1][0], det->p[1][1]);
175 corner_points.emplace_back(det->p[2][0], det->p[2][1]);
176 corner_points.emplace_back(det->p[3][0], det->p[3][1]);
177
178 return corner_points;
179}
180
milind-u99b1a762023-03-12 16:48:32 -0700181AprilRoboticsDetector::DetectionResult AprilRoboticsDetector::DetectTags(
milind-ufc8ab702023-02-26 14:14:39 -0800182 cv::Mat image, aos::monotonic_clock::time_point eof) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800183 const aos::monotonic_clock::time_point start_time =
184 aos::monotonic_clock::now();
185
186 image_u8_t im = {
milind-u09fb1252023-01-28 19:21:41 -0800187 .width = image.cols,
188 .height = image.rows,
189 .stride = image.cols,
190 .buf = image.data,
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800191 };
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800192 const uint32_t min_x = FLAGS_pixel_border;
193 const uint32_t max_x = image.cols - FLAGS_pixel_border;
Jim Ostrowski0197d6b2023-03-04 12:41:13 -0800194 const uint32_t min_y = FLAGS_pixel_border;
195 const uint32_t max_y = image.rows - FLAGS_pixel_border;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800196
197 ftrace_.FormatMessage("Starting detect\n");
198 zarray_t *detections = apriltag_detector_detect(tag_detector_, &im);
199 ftrace_.FormatMessage("Done detecting\n");
200
milind-ufc8ab702023-02-26 14:14:39 -0800201 std::vector<Detection> results;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800202
milind-u7aa29e22023-02-23 20:22:01 -0800203 auto builder = image_annotations_sender_.MakeBuilder();
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800204 std::vector<flatbuffers::Offset<foxglove::PointsAnnotation>> foxglove_corners;
Yash Chainani728ae222023-02-04 19:48:12 -0800205
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800206 for (int i = 0; i < zarray_size(detections); i++) {
207 apriltag_detection_t *det;
208 zarray_get(detections, i, &det);
209
milind-uf2a4e322023-02-01 19:33:10 -0800210 if (det->decision_margin > FLAGS_min_decision_margin) {
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800211 if (det->p[0][0] < min_x || det->p[0][0] > max_x ||
212 det->p[1][0] < min_x || det->p[1][0] > max_x ||
213 det->p[2][0] < min_x || det->p[2][0] > max_x ||
Jim Ostrowski0197d6b2023-03-04 12:41:13 -0800214 det->p[3][0] < min_x || det->p[3][0] > max_x ||
215 det->p[0][1] < min_y || det->p[0][1] > max_y ||
216 det->p[1][1] < min_y || det->p[1][1] > max_y ||
217 det->p[2][1] < min_y || det->p[2][1] > max_y ||
218 det->p[3][1] < min_y || det->p[3][1] > max_y) {
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800219 VLOG(1) << "Rejecting detection because corner is outside pixel border";
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800220 // Send rejected corner points in red
221 std::vector<cv::Point2f> rejected_corner_points = MakeCornerVector(det);
222 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
223 builder.fbb(), eof, rejected_corner_points,
224 std::vector<double>{1.0, 0.0, 0.0, 0.5}));
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800225 continue;
226 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800227 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
228 << " margin: " << det->decision_margin;
229
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800230 // First create an apriltag_detection_info_t struct using your known
231 // parameters.
232 apriltag_detection_info_t info;
233 info.det = det;
234 info.tagsize = 0.1524;
milind-uf2a4e322023-02-01 19:33:10 -0800235
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800236 info.fx = intrinsics_.at<double>(0, 0);
237 info.fy = intrinsics_.at<double>(1, 1);
238 info.cx = intrinsics_.at<double>(0, 2);
239 info.cy = intrinsics_.at<double>(1, 2);
240
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800241 // Send original corner points in green
242 std::vector<cv::Point2f> orig_corner_points = MakeCornerVector(det);
243 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
244 builder.fbb(), eof, orig_corner_points,
245 std::vector<double>{0.0, 1.0, 0.0, 0.5}));
Jim Ostrowskid2b5c912023-02-26 00:59:35 -0800246
milind-ueccac3c2023-02-25 20:54:47 -0800247 UndistortDetection(det);
248
milind-uf5b3b4b2023-02-26 14:50:38 -0800249 const aos::monotonic_clock::time_point before_pose_estimation =
250 aos::monotonic_clock::now();
251
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800252 apriltag_pose_t pose;
milind-uf5b3b4b2023-02-26 14:50:38 -0800253 double pose_error = estimate_tag_pose(&info, &pose);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800254
255 const aos::monotonic_clock::time_point after_pose_estimation =
256 aos::monotonic_clock::now();
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800257 VLOG(1) << "Took "
Austin Schuhd2667932023-02-04 16:22:39 -0800258 << chrono::duration<double>(after_pose_estimation -
259 before_pose_estimation)
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800260 .count()
261 << " seconds for pose estimation";
milind-uf5b3b4b2023-02-26 14:50:38 -0800262 VLOG(1) << "Pose err: " << pose_error;
Yash Chainani728ae222023-02-04 19:48:12 -0800263
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800264 // Send undistorted corner points in pink
265 std::vector<cv::Point2f> corner_points = MakeCornerVector(det);
266 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
267 builder.fbb(), eof, corner_points,
268 std::vector<double>{1.0, 0.75, 0.8, 1.0}));
milind-uf5b3b4b2023-02-26 14:50:38 -0800269
270 double distortion_factor =
271 ComputeDistortionFactor(orig_corner_points, corner_points);
272
273 results.emplace_back(Detection{.det = *det,
274 .pose = pose,
275 .pose_error = pose_error,
276 .distortion_factor = distortion_factor});
milind-u99b1a762023-03-12 16:48:32 -0700277 } else {
278 rejections_++;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800279 }
280 }
281
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800282 const auto corners_offset = builder.fbb()->CreateVector(foxglove_corners);
Yash Chainani10b7b022023-02-22 14:34:04 -0800283 foxglove::ImageAnnotations::Builder annotation_builder(*builder.fbb());
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800284 annotation_builder.add_points(corners_offset);
285 builder.CheckOk(builder.Send(annotation_builder.Finish()));
Yash Chainani728ae222023-02-04 19:48:12 -0800286
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800287 apriltag_detections_destroy(detections);
288
289 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
290
milind-uf3ab8ba2023-02-04 17:56:16 -0800291 if (FLAGS_debug) {
292 timeprofile_display(tag_detector_->tp);
293 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800294
Austin Schuhd2667932023-02-04 16:22:39 -0800295 VLOG(1) << "Took " << chrono::duration<double>(end_time - start_time).count()
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800296 << " seconds to detect overall";
297
milind-u99b1a762023-03-12 16:48:32 -0700298 return {.detections = results, .rejections = rejections_};
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800299}
300
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800301} // namespace vision
302} // namespace y2023