blob: b943db014a8d87b5b2266a02b58335b948045638 [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_(),
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -080024 image_callback_(event_loop, channel_name,
25 [&](cv::Mat image_color_mat,
26 const aos::monotonic_clock::time_point eof) {
27 HandleImage(image_color_mat, eof);
28 },
29 chrono::milliseconds(5)),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080030 target_map_sender_(
Yash Chainani728ae222023-02-04 19:48:12 -080031 event_loop->MakeSender<frc971::vision::TargetMap>("/camera")),
milind-u7aa29e22023-02-23 20:22:01 -080032 image_annotations_sender_(
33 event_loop->MakeSender<foxglove::ImageAnnotations>("/camera")) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080034 tag_family_ = tag16h5_create();
35 tag_detector_ = apriltag_detector_create();
36
37 apriltag_detector_add_family_bits(tag_detector_, tag_family_, 1);
38 tag_detector_->nthreads = 6;
39 tag_detector_->wp = workerpool_create(tag_detector_->nthreads);
40 tag_detector_->qtp.min_white_black_diff = 5;
41 tag_detector_->debug = FLAGS_debug;
42
43 std::string hostname = aos::network::GetHostname();
44
45 // Check team string is valid
James Kuszmauld67f6d22023-02-05 17:37:25 -080046 calibration_ = FindCameraCalibration(
47 calibration_data_.constants(), event_loop->node()->name()->string_view());
milind-uf2a4e322023-02-01 19:33:10 -080048
49 extrinsics_ = CameraExtrinsics(calibration_);
50
Maxwell Hendersonfebee252023-01-28 16:53:52 -080051 intrinsics_ = CameraIntrinsics(calibration_);
milind-uf2a4e322023-02-01 19:33:10 -080052 // Create an undistort projection matrix using the intrinsics
53 projection_matrix_ = cv::Mat::zeros(3, 4, CV_64F);
54 intrinsics_.rowRange(0, 3).colRange(0, 3).copyTo(
55 projection_matrix_.rowRange(0, 3).colRange(0, 3));
56
57 dist_coeffs_ = CameraDistCoeffs(calibration_);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080058
59 image_callback_.set_format(frc971::vision::ImageCallback::Format::GRAYSCALE);
60}
61
62AprilRoboticsDetector::~AprilRoboticsDetector() {
63 apriltag_detector_destroy(tag_detector_);
64 free(tag_family_);
65}
66
67void AprilRoboticsDetector::SetWorkerpoolAffinities() {
68 for (int i = 0; i < tag_detector_->wp->nthreads; i++) {
69 cpu_set_t affinity;
70 CPU_ZERO(&affinity);
71 CPU_SET(i, &affinity);
72 pthread_setaffinity_np(tag_detector_->wp->threads[i], sizeof(affinity),
73 &affinity);
74 struct sched_param param;
75 param.sched_priority = 20;
76 int res = pthread_setschedparam(tag_detector_->wp->threads[i], SCHED_FIFO,
77 &param);
78 PCHECK(res == 0) << "Failed to set priority of threadpool threads";
79 }
80}
81
milind-uf2a4e322023-02-01 19:33:10 -080082void AprilRoboticsDetector::HandleImage(cv::Mat image_grayscale,
milind-u09fb1252023-01-28 19:21:41 -080083 aos::monotonic_clock::time_point eof) {
milind-uf5b3b4b2023-02-26 14:50:38 -080084 image_size_ = image_grayscale.size();
85
milind-ufc8ab702023-02-26 14:14:39 -080086 std::vector<Detection> detections = DetectTags(image_grayscale, eof);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080087
88 auto builder = target_map_sender_.MakeBuilder();
89 std::vector<flatbuffers::Offset<frc971::vision::TargetPoseFbs>> target_poses;
milind-ufc8ab702023-02-26 14:14:39 -080090 for (const auto &detection : detections) {
91 target_poses.emplace_back(BuildTargetPose(detection, builder.fbb()));
Maxwell Hendersonfebee252023-01-28 16:53:52 -080092 }
93 const auto target_poses_offset = builder.fbb()->CreateVector(target_poses);
94 auto target_map_builder = builder.MakeBuilder<frc971::vision::TargetMap>();
Maxwell Hendersonfebee252023-01-28 16:53:52 -080095 target_map_builder.add_target_poses(target_poses_offset);
milind-u09fb1252023-01-28 19:21:41 -080096 target_map_builder.add_monotonic_timestamp_ns(eof.time_since_epoch().count());
Maxwell Hendersonfebee252023-01-28 16:53:52 -080097 builder.CheckOk(builder.Send(target_map_builder.Finish()));
98}
99
100flatbuffers::Offset<frc971::vision::TargetPoseFbs>
milind-ufc8ab702023-02-26 14:14:39 -0800101AprilRoboticsDetector::BuildTargetPose(const Detection &detection,
milind-u681c4712023-02-23 21:22:50 -0800102 flatbuffers::FlatBufferBuilder *fbb) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800103 const auto T =
milind-ufc8ab702023-02-26 14:14:39 -0800104 Eigen::Translation3d(detection.pose.t->data[0], detection.pose.t->data[1],
105 detection.pose.t->data[2]);
milind-u3f5f83c2023-01-29 15:23:51 -0800106 const auto position_offset =
107 frc971::vision::CreatePosition(*fbb, T.x(), T.y(), T.z());
108
milind-u633c4c02023-02-25 22:51:45 -0800109 // Aprilrobotics stores the rotation matrix in row-major order
110 const auto orientation = Eigen::Quaterniond(
milind-ufc8ab702023-02-26 14:14:39 -0800111 Eigen::Matrix<double, 3, 3, Eigen::RowMajor>(detection.pose.R->data));
milind-u3f5f83c2023-01-29 15:23:51 -0800112 const auto orientation_offset = frc971::vision::CreateQuaternion(
113 *fbb, orientation.w(), orientation.x(), orientation.y(), orientation.z());
114
milind-u681c4712023-02-23 21:22:50 -0800115 return frc971::vision::CreateTargetPoseFbs(
milind-ufc8ab702023-02-26 14:14:39 -0800116 *fbb, detection.det.id, position_offset, orientation_offset,
milind-uf5b3b4b2023-02-26 14:50:38 -0800117 detection.det.decision_margin, detection.pose_error,
118 detection.distortion_factor);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800119}
120
milind-uf2a4e322023-02-01 19:33:10 -0800121void AprilRoboticsDetector::UndistortDetection(
122 apriltag_detection_t *det) const {
123 // 4 corners
124 constexpr size_t kRows = 4;
125 // 2d points
126 constexpr size_t kCols = 2;
127
128 cv::Mat distorted_points(kRows, kCols, CV_64F, det->p);
129 cv::Mat undistorted_points = cv::Mat::zeros(kRows, kCols, CV_64F);
130
131 // Undistort the april tag points
132 cv::undistortPoints(distorted_points, undistorted_points, intrinsics_,
133 dist_coeffs_, cv::noArray(), projection_matrix_);
134
135 // Copy the undistorted points into det
136 for (size_t i = 0; i < kRows; i++) {
137 for (size_t j = 0; j < kCols; j++) {
138 det->p[i][j] = undistorted_points.at<double>(i, j);
139 }
140 }
141}
142
milind-uf5b3b4b2023-02-26 14:50:38 -0800143double AprilRoboticsDetector::ComputeDistortionFactor(
144 const std::vector<cv::Point2f> &orig_corners,
145 const std::vector<cv::Point2f> &corners) {
146 CHECK_EQ(orig_corners.size(), 4ul);
147 CHECK_EQ(corners.size(), 4ul);
148
149 double avg_distance = 0.0;
150 for (size_t i = 0; i < corners.size(); i++) {
151 avg_distance += cv::norm(orig_corners[i] - corners[i]);
152 }
153 avg_distance /= corners.size();
154
155 // Normalize avg_distance by dividing by the image size
156 double distortion_factor =
157 avg_distance /
158 static_cast<double>(image_size_.width * image_size_.height);
159 return distortion_factor;
160}
161
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800162std::vector<cv::Point2f> AprilRoboticsDetector::MakeCornerVector(
163 const apriltag_detection_t *det) {
164 std::vector<cv::Point2f> corner_points;
165 corner_points.emplace_back(det->p[0][0], det->p[0][1]);
166 corner_points.emplace_back(det->p[1][0], det->p[1][1]);
167 corner_points.emplace_back(det->p[2][0], det->p[2][1]);
168 corner_points.emplace_back(det->p[3][0], det->p[3][1]);
169
170 return corner_points;
171}
172
milind-ufc8ab702023-02-26 14:14:39 -0800173std::vector<AprilRoboticsDetector::Detection> AprilRoboticsDetector::DetectTags(
174 cv::Mat image, aos::monotonic_clock::time_point eof) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800175 const aos::monotonic_clock::time_point start_time =
176 aos::monotonic_clock::now();
177
178 image_u8_t im = {
milind-u09fb1252023-01-28 19:21:41 -0800179 .width = image.cols,
180 .height = image.rows,
181 .stride = image.cols,
182 .buf = image.data,
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800183 };
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800184 const uint32_t min_x = FLAGS_pixel_border;
185 const uint32_t max_x = image.cols - FLAGS_pixel_border;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800186
187 ftrace_.FormatMessage("Starting detect\n");
188 zarray_t *detections = apriltag_detector_detect(tag_detector_, &im);
189 ftrace_.FormatMessage("Done detecting\n");
190
milind-ufc8ab702023-02-26 14:14:39 -0800191 std::vector<Detection> results;
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800192
milind-u7aa29e22023-02-23 20:22:01 -0800193 auto builder = image_annotations_sender_.MakeBuilder();
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800194 std::vector<flatbuffers::Offset<foxglove::PointsAnnotation>> foxglove_corners;
Yash Chainani728ae222023-02-04 19:48:12 -0800195
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800196 for (int i = 0; i < zarray_size(detections); i++) {
197 apriltag_detection_t *det;
198 zarray_get(detections, i, &det);
199
milind-uf2a4e322023-02-01 19:33:10 -0800200 if (det->decision_margin > FLAGS_min_decision_margin) {
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800201 // TODO<jim>: Should we check for top/bottom of image?
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800202 if (det->p[0][0] < min_x || det->p[0][0] > max_x ||
203 det->p[1][0] < min_x || det->p[1][0] > max_x ||
204 det->p[2][0] < min_x || det->p[2][0] > max_x ||
205 det->p[3][0] < min_x || det->p[3][0] > max_x) {
206 VLOG(1) << "Rejecting detection because corner is outside pixel border";
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800207 // Send rejected corner points in red
208 std::vector<cv::Point2f> rejected_corner_points = MakeCornerVector(det);
209 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
210 builder.fbb(), eof, rejected_corner_points,
211 std::vector<double>{1.0, 0.0, 0.0, 0.5}));
Jim Ostrowski437b1fb2023-02-26 10:12:01 -0800212 continue;
213 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800214 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
215 << " margin: " << det->decision_margin;
216
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800217 // First create an apriltag_detection_info_t struct using your known
218 // parameters.
219 apriltag_detection_info_t info;
220 info.det = det;
221 info.tagsize = 0.1524;
milind-uf2a4e322023-02-01 19:33:10 -0800222
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800223 info.fx = intrinsics_.at<double>(0, 0);
224 info.fy = intrinsics_.at<double>(1, 1);
225 info.cx = intrinsics_.at<double>(0, 2);
226 info.cy = intrinsics_.at<double>(1, 2);
227
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800228 // Send original corner points in green
229 std::vector<cv::Point2f> orig_corner_points = MakeCornerVector(det);
230 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
231 builder.fbb(), eof, orig_corner_points,
232 std::vector<double>{0.0, 1.0, 0.0, 0.5}));
Jim Ostrowskid2b5c912023-02-26 00:59:35 -0800233
milind-ueccac3c2023-02-25 20:54:47 -0800234 UndistortDetection(det);
235
milind-uf5b3b4b2023-02-26 14:50:38 -0800236 const aos::monotonic_clock::time_point before_pose_estimation =
237 aos::monotonic_clock::now();
238
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800239 apriltag_pose_t pose;
milind-uf5b3b4b2023-02-26 14:50:38 -0800240 double pose_error = estimate_tag_pose(&info, &pose);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800241
242 const aos::monotonic_clock::time_point after_pose_estimation =
243 aos::monotonic_clock::now();
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800244 VLOG(1) << "Took "
Austin Schuhd2667932023-02-04 16:22:39 -0800245 << chrono::duration<double>(after_pose_estimation -
246 before_pose_estimation)
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800247 .count()
248 << " seconds for pose estimation";
milind-uf5b3b4b2023-02-26 14:50:38 -0800249 VLOG(1) << "Pose err: " << pose_error;
Yash Chainani728ae222023-02-04 19:48:12 -0800250
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800251 // Send undistorted corner points in pink
252 std::vector<cv::Point2f> corner_points = MakeCornerVector(det);
253 foxglove_corners.push_back(frc971::vision::BuildPointsAnnotation(
254 builder.fbb(), eof, corner_points,
255 std::vector<double>{1.0, 0.75, 0.8, 1.0}));
milind-uf5b3b4b2023-02-26 14:50:38 -0800256
257 double distortion_factor =
258 ComputeDistortionFactor(orig_corner_points, corner_points);
259
260 results.emplace_back(Detection{.det = *det,
261 .pose = pose,
262 .pose_error = pose_error,
263 .distortion_factor = distortion_factor});
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800264 }
265 }
266
Jim Ostrowski5e2c5e62023-02-26 12:52:56 -0800267 foxglove::ImageAnnotations::Builder annotation_builder(*builder.fbb());
268 const auto corners_offset = builder.fbb()->CreateVector(foxglove_corners);
269 annotation_builder.add_points(corners_offset);
270 builder.CheckOk(builder.Send(annotation_builder.Finish()));
Yash Chainani728ae222023-02-04 19:48:12 -0800271
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800272 apriltag_detections_destroy(detections);
273
274 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
275
milind-uf3ab8ba2023-02-04 17:56:16 -0800276 if (FLAGS_debug) {
277 timeprofile_display(tag_detector_->tp);
278 }
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800279
Austin Schuhd2667932023-02-04 16:22:39 -0800280 VLOG(1) << "Took " << chrono::duration<double>(end_time - start_time).count()
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800281 << " seconds to detect overall";
282
283 return results;
284}
285
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800286} // namespace vision
287} // namespace y2023