blob: 01025385b0044759a00bffe92d40888be4e20769 [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-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_(),
milind-ufc8ab702023-02-26 14:14:39 -080029 image_callback_(
30 event_loop, channel_name,
31 [&](cv::Mat image_color_mat,
32 const aos::monotonic_clock::time_point eof) {
33 HandleImage(image_color_mat, eof);
34 },
35 chrono::milliseconds(5)),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080036 target_map_sender_(
Yash Chainani728ae222023-02-04 19:48:12 -080037 event_loop->MakeSender<frc971::vision::TargetMap>("/camera")),
milind-u7aa29e22023-02-23 20:22:01 -080038 image_annotations_sender_(
39 event_loop->MakeSender<foxglove::ImageAnnotations>("/camera")) {
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-ufc8ab702023-02-26 14:14:39 -080092 std::vector<Detection> detections = 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-ufc8ab702023-02-26 14:14:39 -080096 for (const auto &detection : detections) {
97 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());
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800103 builder.CheckOk(builder.Send(target_map_builder.Finish()));
104}
105
106flatbuffers::Offset<frc971::vision::TargetPoseFbs>
milind-ufc8ab702023-02-26 14:14:39 -0800107AprilRoboticsDetector::BuildTargetPose(const Detection &detection,
milind-u681c4712023-02-23 21:22:50 -0800108 flatbuffers::FlatBufferBuilder *fbb) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800109 const auto T =
milind-ufc8ab702023-02-26 14:14:39 -0800110 Eigen::Translation3d(detection.pose.t->data[0], detection.pose.t->data[1],
111 detection.pose.t->data[2]);
milind-u3f5f83c2023-01-29 15:23:51 -0800112 const auto position_offset =
113 frc971::vision::CreatePosition(*fbb, T.x(), T.y(), T.z());
114
milind-u633c4c02023-02-25 22:51:45 -0800115 // Aprilrobotics stores the rotation matrix in row-major order
116 const auto orientation = Eigen::Quaterniond(
milind-ufc8ab702023-02-26 14:14:39 -0800117 Eigen::Matrix<double, 3, 3, Eigen::RowMajor>(detection.pose.R->data));
milind-u3f5f83c2023-01-29 15:23:51 -0800118 const auto orientation_offset = frc971::vision::CreateQuaternion(
119 *fbb, orientation.w(), orientation.x(), orientation.y(), orientation.z());
120
milind-u681c4712023-02-23 21:22:50 -0800121 return frc971::vision::CreateTargetPoseFbs(
milind-ufc8ab702023-02-26 14:14:39 -0800122 *fbb, detection.det.id, position_offset, orientation_offset,
milind-uf5b3b4b2023-02-26 14:50:38 -0800123 detection.det.decision_margin, detection.pose_error,
124 detection.distortion_factor);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800125}
126
milind-uf2a4e322023-02-01 19:33:10 -0800127void AprilRoboticsDetector::UndistortDetection(
128 apriltag_detection_t *det) const {
129 // 4 corners
130 constexpr size_t kRows = 4;
131 // 2d points
132 constexpr size_t kCols = 2;
133
134 cv::Mat distorted_points(kRows, kCols, CV_64F, det->p);
135 cv::Mat undistorted_points = cv::Mat::zeros(kRows, kCols, CV_64F);
136
137 // Undistort the april tag points
138 cv::undistortPoints(distorted_points, undistorted_points, intrinsics_,
139 dist_coeffs_, cv::noArray(), projection_matrix_);
140
141 // Copy the undistorted points into det
142 for (size_t i = 0; i < kRows; i++) {
143 for (size_t j = 0; j < kCols; j++) {
144 det->p[i][j] = undistorted_points.at<double>(i, j);
145 }
146 }
147}
148
milind-uf5b3b4b2023-02-26 14:50:38 -0800149double AprilRoboticsDetector::ComputeDistortionFactor(
150 const std::vector<cv::Point2f> &orig_corners,
151 const std::vector<cv::Point2f> &corners) {
152 CHECK_EQ(orig_corners.size(), 4ul);
153 CHECK_EQ(corners.size(), 4ul);
154
155 double avg_distance = 0.0;
156 for (size_t i = 0; i < corners.size(); i++) {
157 avg_distance += cv::norm(orig_corners[i] - corners[i]);
158 }
159 avg_distance /= corners.size();
160
milind-u60e7fe52023-02-26 16:13:50 -0800161 // Normalize avg_distance by dividing by the image size, and then the maximum
162 // expected distortion
milind-uf5b3b4b2023-02-26 14:50:38 -0800163 double distortion_factor =
164 avg_distance /
165 static_cast<double>(image_size_.width * image_size_.height);
milind-u60e7fe52023-02-26 16:13:50 -0800166 return std::min(distortion_factor / FLAGS_max_expected_distortion, 1.0);
milind-uf5b3b4b2023-02-26 14:50:38 -0800167}
168
milind-ufc8ab702023-02-26 14:14:39 -0800169std::vector<AprilRoboticsDetector::Detection> AprilRoboticsDetector::DetectTags(
170 cv::Mat image, aos::monotonic_clock::time_point eof) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800171 const aos::monotonic_clock::time_point start_time =
172 aos::monotonic_clock::now();
173
174 image_u8_t im = {
milind-u09fb1252023-01-28 19:21:41 -0800175 .width = image.cols,
176 .height = image.rows,
177 .stride = image.cols,
178 .buf = image.data,
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800179 };
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800180 const uint32_t min_x = FLAGS_pixel_border;
181 const uint32_t max_x = image.cols - FLAGS_pixel_border;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800182
183 ftrace_.FormatMessage("Starting detect\n");
184 zarray_t *detections = apriltag_detector_detect(tag_detector_, &im);
185 ftrace_.FormatMessage("Done detecting\n");
186
milind-ufc8ab702023-02-26 14:14:39 -0800187 std::vector<Detection> results;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800188
Jim Ostrowskid2b5c912023-02-26 00:59:35 -0800189 std::vector<std::vector<cv::Point2f>> orig_corners_vector;
milind-u7aa29e22023-02-23 20:22:01 -0800190 std::vector<std::vector<cv::Point2f>> corners_vector;
Yash Chainani728ae222023-02-04 19:48:12 -0800191
milind-u7aa29e22023-02-23 20:22:01 -0800192 auto builder = image_annotations_sender_.MakeBuilder();
Yash Chainani728ae222023-02-04 19:48:12 -0800193
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800194 for (int i = 0; i < zarray_size(detections); i++) {
195 apriltag_detection_t *det;
196 zarray_get(detections, i, &det);
197
milind-uf2a4e322023-02-01 19:33:10 -0800198 if (det->decision_margin > FLAGS_min_decision_margin) {
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800199 if (det->p[0][0] < min_x || det->p[0][0] > max_x ||
200 det->p[1][0] < min_x || det->p[1][0] > max_x ||
201 det->p[2][0] < min_x || det->p[2][0] > max_x ||
202 det->p[3][0] < min_x || det->p[3][0] > max_x) {
203 VLOG(1) << "Rejecting detection because corner is outside pixel border";
204 continue;
205 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800206 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
207 << " margin: " << det->decision_margin;
208
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800209 // First create an apriltag_detection_info_t struct using your known
210 // parameters.
211 apriltag_detection_info_t info;
212 info.det = det;
213 info.tagsize = 0.1524;
milind-uf2a4e322023-02-01 19:33:10 -0800214
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800215 info.fx = intrinsics_.at<double>(0, 0);
216 info.fy = intrinsics_.at<double>(1, 1);
217 info.cx = intrinsics_.at<double>(0, 2);
218 info.cy = intrinsics_.at<double>(1, 2);
219
Jim Ostrowskid2b5c912023-02-26 00:59:35 -0800220 // Store out the original, pre-undistortion corner points for sending
221 std::vector<cv::Point2f> orig_corner_points;
222 orig_corner_points.emplace_back(det->p[0][0], det->p[0][1]);
223 orig_corner_points.emplace_back(det->p[1][0], det->p[1][1]);
224 orig_corner_points.emplace_back(det->p[2][0], det->p[2][1]);
225 orig_corner_points.emplace_back(det->p[3][0], det->p[3][1]);
226
227 orig_corners_vector.emplace_back(orig_corner_points);
228
milind-ueccac3c2023-02-25 20:54:47 -0800229 UndistortDetection(det);
230
milind-uf5b3b4b2023-02-26 14:50:38 -0800231 const aos::monotonic_clock::time_point before_pose_estimation =
232 aos::monotonic_clock::now();
233
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800234 apriltag_pose_t pose;
milind-uf5b3b4b2023-02-26 14:50:38 -0800235 double pose_error = estimate_tag_pose(&info, &pose);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800236
237 const aos::monotonic_clock::time_point after_pose_estimation =
238 aos::monotonic_clock::now();
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800239 VLOG(1) << "Took "
Austin Schuhd2667932023-02-04 16:22:39 -0800240 << chrono::duration<double>(after_pose_estimation -
241 before_pose_estimation)
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800242 .count()
243 << " seconds for pose estimation";
milind-uf5b3b4b2023-02-26 14:50:38 -0800244 VLOG(1) << "Pose err: " << pose_error;
Yash Chainani728ae222023-02-04 19:48:12 -0800245
milind-u7aa29e22023-02-23 20:22:01 -0800246 std::vector<cv::Point2f> corner_points;
Yash Chainani728ae222023-02-04 19:48:12 -0800247 corner_points.emplace_back(det->p[0][0], det->p[0][1]);
248 corner_points.emplace_back(det->p[1][0], det->p[1][1]);
249 corner_points.emplace_back(det->p[2][0], det->p[2][1]);
250 corner_points.emplace_back(det->p[3][0], det->p[3][1]);
251
milind-u7aa29e22023-02-23 20:22:01 -0800252 corners_vector.emplace_back(corner_points);
milind-uf5b3b4b2023-02-26 14:50:38 -0800253
254 double distortion_factor =
255 ComputeDistortionFactor(orig_corner_points, corner_points);
256
257 results.emplace_back(Detection{.det = *det,
258 .pose = pose,
259 .pose_error = pose_error,
260 .distortion_factor = distortion_factor});
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800261 }
262 }
263
Jim Ostrowskid2b5c912023-02-26 00:59:35 -0800264 const auto annotations_offset = frc971::vision::BuildAnnotations(
265 eof, orig_corners_vector, 5.0, builder.fbb());
milind-u7aa29e22023-02-23 20:22:01 -0800266 builder.CheckOk(builder.Send(annotations_offset));
Yash Chainani728ae222023-02-04 19:48:12 -0800267
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800268 apriltag_detections_destroy(detections);
269
270 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
271
milind-uf3ab8ba2023-02-04 17:56:16 -0800272 if (FLAGS_debug) {
273 timeprofile_display(tag_detector_->tp);
274 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800275
Austin Schuhd2667932023-02-04 16:22:39 -0800276 VLOG(1) << "Took " << chrono::duration<double>(end_time - start_time).count()
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800277 << " seconds to detect overall";
278
279 return results;
280}
281
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800282} // namespace vision
283} // namespace y2023