blob: 23c5ada3e8f839aaa77784c710f11fadbbdc2cb4 [file] [log] [blame]
Maxwell Hendersonfebee252023-01-28 16:53:52 -08001#include "y2023/vision/aprilrobotics.h"
2
Maxwell Hendersonfebee252023-01-28 16:53:52 -08003DEFINE_bool(
4 debug, false,
5 "If true, dump a ton of debug and crash on the first valid detection.");
6
7DEFINE_int32(team_number, 971,
8 "Use the calibration for a node with this team number");
9namespace y2023 {
10namespace vision {
11
Austin Schuhd2667932023-02-04 16:22:39 -080012namespace chrono = std::chrono;
13
Maxwell Hendersonfebee252023-01-28 16:53:52 -080014AprilRoboticsDetector::AprilRoboticsDetector(aos::EventLoop *event_loop,
15 std::string_view channel_name)
16 : calibration_data_(CalibrationData()),
17 ftrace_(),
Austin Schuhd2667932023-02-04 16:22:39 -080018 image_callback_(
19 event_loop, channel_name,
20 [&](cv::Mat image_color_mat,
21 const aos::monotonic_clock::time_point eof) {
22 HandleImage(image_color_mat, eof);
23 },
24 chrono::milliseconds(5)),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080025 target_map_sender_(
Yash Chainani728ae222023-02-04 19:48:12 -080026 event_loop->MakeSender<frc971::vision::TargetMap>("/camera")),
27 april_debug_sender_(
28 event_loop->MakeSender<y2023::vision::AprilDebug>("/camera")) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080029 tag_family_ = tag16h5_create();
30 tag_detector_ = apriltag_detector_create();
31
32 apriltag_detector_add_family_bits(tag_detector_, tag_family_, 1);
33 tag_detector_->nthreads = 6;
34 tag_detector_->wp = workerpool_create(tag_detector_->nthreads);
35 tag_detector_->qtp.min_white_black_diff = 5;
36 tag_detector_->debug = FLAGS_debug;
37
38 std::string hostname = aos::network::GetHostname();
39
40 // Check team string is valid
41 std::optional<uint16_t> pi_number = aos::network::ParsePiNumber(hostname);
42 std::optional<uint16_t> team_number =
43 aos::network::team_number_internal::ParsePiTeamNumber(hostname);
44 CHECK(pi_number) << "Unable to parse pi number from '" << hostname << "'";
45 CHECK(team_number);
46
47 calibration_ = FindCameraCalibration(&calibration_data_.message(),
48 "pi" + std::to_string(*pi_number));
49 intrinsics_ = CameraIntrinsics(calibration_);
50 camera_distortion_coeffs_ = CameraDistCoeffs(calibration_);
51
52 image_callback_.set_format(frc971::vision::ImageCallback::Format::GRAYSCALE);
53}
54
55AprilRoboticsDetector::~AprilRoboticsDetector() {
56 apriltag_detector_destroy(tag_detector_);
57 free(tag_family_);
58}
59
60void AprilRoboticsDetector::SetWorkerpoolAffinities() {
61 for (int i = 0; i < tag_detector_->wp->nthreads; i++) {
62 cpu_set_t affinity;
63 CPU_ZERO(&affinity);
64 CPU_SET(i, &affinity);
65 pthread_setaffinity_np(tag_detector_->wp->threads[i], sizeof(affinity),
66 &affinity);
67 struct sched_param param;
68 param.sched_priority = 20;
69 int res = pthread_setschedparam(tag_detector_->wp->threads[i], SCHED_FIFO,
70 &param);
71 PCHECK(res == 0) << "Failed to set priority of threadpool threads";
72 }
73}
74
milind-u09fb1252023-01-28 19:21:41 -080075void AprilRoboticsDetector::HandleImage(cv::Mat image_color_mat,
76 aos::monotonic_clock::time_point eof) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080077 std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>> detections =
78 DetectTags(image_color_mat);
79
80 auto builder = target_map_sender_.MakeBuilder();
81 std::vector<flatbuffers::Offset<frc971::vision::TargetPoseFbs>> target_poses;
82 for (const auto &[detection, pose] : detections) {
83 target_poses.emplace_back(
84 BuildTargetPose(pose, detection.id, builder.fbb()));
85 }
86 const auto target_poses_offset = builder.fbb()->CreateVector(target_poses);
87 auto target_map_builder = builder.MakeBuilder<frc971::vision::TargetMap>();
Maxwell Hendersonfebee252023-01-28 16:53:52 -080088 target_map_builder.add_target_poses(target_poses_offset);
milind-u09fb1252023-01-28 19:21:41 -080089 target_map_builder.add_monotonic_timestamp_ns(eof.time_since_epoch().count());
Maxwell Hendersonfebee252023-01-28 16:53:52 -080090 builder.CheckOk(builder.Send(target_map_builder.Finish()));
91}
92
93flatbuffers::Offset<frc971::vision::TargetPoseFbs>
94AprilRoboticsDetector::BuildTargetPose(
95 const apriltag_pose_t &pose,
96 frc971::vision::TargetMapper::TargetId target_id,
97 flatbuffers::FlatBufferBuilder *fbb) {
98 const auto T =
99 Eigen::Translation3d(pose.t->data[0], pose.t->data[1], pose.t->data[2]);
milind-u3f5f83c2023-01-29 15:23:51 -0800100 const auto position_offset =
101 frc971::vision::CreatePosition(*fbb, T.x(), T.y(), T.z());
102
103 const auto orientation = Eigen::Quaterniond(Eigen::Matrix3d(pose.R->data));
104 const auto orientation_offset = frc971::vision::CreateQuaternion(
105 *fbb, orientation.w(), orientation.x(), orientation.y(), orientation.z());
106
107 return frc971::vision::CreateTargetPoseFbs(*fbb, target_id, position_offset,
108 orientation_offset);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800109}
110
111std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>>
112AprilRoboticsDetector::DetectTags(cv::Mat image) {
113 const aos::monotonic_clock::time_point start_time =
114 aos::monotonic_clock::now();
115
116 image_u8_t im = {
milind-u09fb1252023-01-28 19:21:41 -0800117 .width = image.cols,
118 .height = image.rows,
119 .stride = image.cols,
120 .buf = image.data,
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800121 };
122
123 ftrace_.FormatMessage("Starting detect\n");
124 zarray_t *detections = apriltag_detector_detect(tag_detector_, &im);
125 ftrace_.FormatMessage("Done detecting\n");
126
127 std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>> results;
128
Yash Chainani728ae222023-02-04 19:48:12 -0800129 std::vector<flatbuffers::Offset<AprilCorners>> corners_vector;
130
131 auto builder = april_debug_sender_.MakeBuilder();
132
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800133 for (int i = 0; i < zarray_size(detections); i++) {
134 apriltag_detection_t *det;
135 zarray_get(detections, i, &det);
136
137 if (det->decision_margin > 30) {
138 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
139 << " margin: " << det->decision_margin;
140
141 const aos::monotonic_clock::time_point before_pose_estimation =
142 aos::monotonic_clock::now();
143 // First create an apriltag_detection_info_t struct using your known
144 // parameters.
145 apriltag_detection_info_t info;
146 info.det = det;
147 info.tagsize = 0.1524;
148 info.fx = intrinsics_.at<double>(0, 0);
149 info.fy = intrinsics_.at<double>(1, 1);
150 info.cx = intrinsics_.at<double>(0, 2);
151 info.cy = intrinsics_.at<double>(1, 2);
152
153 apriltag_pose_t pose;
154 double err = estimate_tag_pose(&info, &pose);
155
156 VLOG(1) << "err: " << err;
157
158 results.emplace_back(*det, pose);
159
160 const aos::monotonic_clock::time_point after_pose_estimation =
161 aos::monotonic_clock::now();
162
163 VLOG(1) << "Took "
Austin Schuhd2667932023-02-04 16:22:39 -0800164 << chrono::duration<double>(after_pose_estimation -
165 before_pose_estimation)
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800166 .count()
167 << " seconds for pose estimation";
Yash Chainani728ae222023-02-04 19:48:12 -0800168
169 std::vector<Point> corner_points;
170
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 auto corner_points_fbs =
177 builder.fbb()->CreateVectorOfStructs(corner_points);
178
179 AprilCorners::Builder april_corners_builder =
180 builder.MakeBuilder<AprilCorners>();
181
182 april_corners_builder.add_id(det->id);
183 april_corners_builder.add_points(corner_points_fbs);
184
185 corners_vector.emplace_back(april_corners_builder.Finish());
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800186 }
187 }
188
Yash Chainani728ae222023-02-04 19:48:12 -0800189 auto corners_vector_fbs = builder.fbb()->CreateVector(corners_vector);
190
191 AprilDebug::Builder april_debug_builder = builder.MakeBuilder<AprilDebug>();
192
193 april_debug_builder.add_corners(corners_vector_fbs);
194
195 builder.CheckOk(builder.Send(april_debug_builder.Finish()));
196
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800197 apriltag_detections_destroy(detections);
198
199 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
200
201 timeprofile_display(tag_detector_->tp);
202
Austin Schuhd2667932023-02-04 16:22:39 -0800203 VLOG(1) << "Took " << chrono::duration<double>(end_time - start_time).count()
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800204 << " seconds to detect overall";
205
206 return results;
207}
208
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800209} // namespace vision
210} // namespace y2023