blob: fbbc01d19edaff120f60a3114804b5a42e144cdd [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
12AprilRoboticsDetector::AprilRoboticsDetector(aos::EventLoop *event_loop,
13 std::string_view channel_name)
14 : calibration_data_(CalibrationData()),
15 ftrace_(),
16 image_callback_(event_loop, channel_name,
17 [&](cv::Mat image_color_mat,
milind-u09fb1252023-01-28 19:21:41 -080018 const aos::monotonic_clock::time_point eof) {
19 HandleImage(image_color_mat, eof);
Maxwell Hendersonfebee252023-01-28 16:53:52 -080020 }),
21 target_map_sender_(
Yash Chainani728ae222023-02-04 19:48:12 -080022 event_loop->MakeSender<frc971::vision::TargetMap>("/camera")),
23 april_debug_sender_(
24 event_loop->MakeSender<y2023::vision::AprilDebug>("/camera")) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080025 tag_family_ = tag16h5_create();
26 tag_detector_ = apriltag_detector_create();
27
28 apriltag_detector_add_family_bits(tag_detector_, tag_family_, 1);
29 tag_detector_->nthreads = 6;
30 tag_detector_->wp = workerpool_create(tag_detector_->nthreads);
31 tag_detector_->qtp.min_white_black_diff = 5;
32 tag_detector_->debug = FLAGS_debug;
33
34 std::string hostname = aos::network::GetHostname();
35
36 // Check team string is valid
37 std::optional<uint16_t> pi_number = aos::network::ParsePiNumber(hostname);
38 std::optional<uint16_t> team_number =
39 aos::network::team_number_internal::ParsePiTeamNumber(hostname);
40 CHECK(pi_number) << "Unable to parse pi number from '" << hostname << "'";
41 CHECK(team_number);
42
43 calibration_ = FindCameraCalibration(&calibration_data_.message(),
44 "pi" + std::to_string(*pi_number));
45 intrinsics_ = CameraIntrinsics(calibration_);
46 camera_distortion_coeffs_ = CameraDistCoeffs(calibration_);
47
48 image_callback_.set_format(frc971::vision::ImageCallback::Format::GRAYSCALE);
49}
50
51AprilRoboticsDetector::~AprilRoboticsDetector() {
52 apriltag_detector_destroy(tag_detector_);
53 free(tag_family_);
54}
55
56void AprilRoboticsDetector::SetWorkerpoolAffinities() {
57 for (int i = 0; i < tag_detector_->wp->nthreads; i++) {
58 cpu_set_t affinity;
59 CPU_ZERO(&affinity);
60 CPU_SET(i, &affinity);
61 pthread_setaffinity_np(tag_detector_->wp->threads[i], sizeof(affinity),
62 &affinity);
63 struct sched_param param;
64 param.sched_priority = 20;
65 int res = pthread_setschedparam(tag_detector_->wp->threads[i], SCHED_FIFO,
66 &param);
67 PCHECK(res == 0) << "Failed to set priority of threadpool threads";
68 }
69}
70
milind-u09fb1252023-01-28 19:21:41 -080071void AprilRoboticsDetector::HandleImage(cv::Mat image_color_mat,
72 aos::monotonic_clock::time_point eof) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080073 std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>> detections =
74 DetectTags(image_color_mat);
75
76 auto builder = target_map_sender_.MakeBuilder();
77 std::vector<flatbuffers::Offset<frc971::vision::TargetPoseFbs>> target_poses;
78 for (const auto &[detection, pose] : detections) {
79 target_poses.emplace_back(
80 BuildTargetPose(pose, detection.id, builder.fbb()));
81 }
82 const auto target_poses_offset = builder.fbb()->CreateVector(target_poses);
83 auto target_map_builder = builder.MakeBuilder<frc971::vision::TargetMap>();
Maxwell Hendersonfebee252023-01-28 16:53:52 -080084 target_map_builder.add_target_poses(target_poses_offset);
milind-u09fb1252023-01-28 19:21:41 -080085 target_map_builder.add_monotonic_timestamp_ns(eof.time_since_epoch().count());
Maxwell Hendersonfebee252023-01-28 16:53:52 -080086 builder.CheckOk(builder.Send(target_map_builder.Finish()));
87}
88
89flatbuffers::Offset<frc971::vision::TargetPoseFbs>
90AprilRoboticsDetector::BuildTargetPose(
91 const apriltag_pose_t &pose,
92 frc971::vision::TargetMapper::TargetId target_id,
93 flatbuffers::FlatBufferBuilder *fbb) {
94 const auto T =
95 Eigen::Translation3d(pose.t->data[0], pose.t->data[1], pose.t->data[2]);
milind-u3f5f83c2023-01-29 15:23:51 -080096 const auto position_offset =
97 frc971::vision::CreatePosition(*fbb, T.x(), T.y(), T.z());
98
99 const auto orientation = Eigen::Quaterniond(Eigen::Matrix3d(pose.R->data));
100 const auto orientation_offset = frc971::vision::CreateQuaternion(
101 *fbb, orientation.w(), orientation.x(), orientation.y(), orientation.z());
102
103 return frc971::vision::CreateTargetPoseFbs(*fbb, target_id, position_offset,
104 orientation_offset);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800105}
106
107std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>>
108AprilRoboticsDetector::DetectTags(cv::Mat image) {
109 const aos::monotonic_clock::time_point start_time =
110 aos::monotonic_clock::now();
111
112 image_u8_t im = {
milind-u09fb1252023-01-28 19:21:41 -0800113 .width = image.cols,
114 .height = image.rows,
115 .stride = image.cols,
116 .buf = image.data,
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800117 };
118
119 ftrace_.FormatMessage("Starting detect\n");
120 zarray_t *detections = apriltag_detector_detect(tag_detector_, &im);
121 ftrace_.FormatMessage("Done detecting\n");
122
123 std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>> results;
124
Yash Chainani728ae222023-02-04 19:48:12 -0800125 std::vector<flatbuffers::Offset<AprilCorners>> corners_vector;
126
127 auto builder = april_debug_sender_.MakeBuilder();
128
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800129 for (int i = 0; i < zarray_size(detections); i++) {
130 apriltag_detection_t *det;
131 zarray_get(detections, i, &det);
132
133 if (det->decision_margin > 30) {
134 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
135 << " margin: " << det->decision_margin;
136
137 const aos::monotonic_clock::time_point before_pose_estimation =
138 aos::monotonic_clock::now();
139 // First create an apriltag_detection_info_t struct using your known
140 // parameters.
141 apriltag_detection_info_t info;
142 info.det = det;
143 info.tagsize = 0.1524;
144 info.fx = intrinsics_.at<double>(0, 0);
145 info.fy = intrinsics_.at<double>(1, 1);
146 info.cx = intrinsics_.at<double>(0, 2);
147 info.cy = intrinsics_.at<double>(1, 2);
148
149 apriltag_pose_t pose;
150 double err = estimate_tag_pose(&info, &pose);
151
152 VLOG(1) << "err: " << err;
153
154 results.emplace_back(*det, pose);
155
156 const aos::monotonic_clock::time_point after_pose_estimation =
157 aos::monotonic_clock::now();
158
159 VLOG(1) << "Took "
160 << std::chrono::duration<double>(after_pose_estimation -
161 before_pose_estimation)
162 .count()
163 << " seconds for pose estimation";
Yash Chainani728ae222023-02-04 19:48:12 -0800164
165 std::vector<Point> corner_points;
166
167 corner_points.emplace_back(det->p[0][0], det->p[0][1]);
168 corner_points.emplace_back(det->p[1][0], det->p[1][1]);
169 corner_points.emplace_back(det->p[2][0], det->p[2][1]);
170 corner_points.emplace_back(det->p[3][0], det->p[3][1]);
171
172 auto corner_points_fbs =
173 builder.fbb()->CreateVectorOfStructs(corner_points);
174
175 AprilCorners::Builder april_corners_builder =
176 builder.MakeBuilder<AprilCorners>();
177
178 april_corners_builder.add_id(det->id);
179 april_corners_builder.add_points(corner_points_fbs);
180
181 corners_vector.emplace_back(april_corners_builder.Finish());
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800182 }
183 }
184
Yash Chainani728ae222023-02-04 19:48:12 -0800185 auto corners_vector_fbs = builder.fbb()->CreateVector(corners_vector);
186
187 AprilDebug::Builder april_debug_builder = builder.MakeBuilder<AprilDebug>();
188
189 april_debug_builder.add_corners(corners_vector_fbs);
190
191 builder.CheckOk(builder.Send(april_debug_builder.Finish()));
192
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800193 apriltag_detections_destroy(detections);
194
195 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
196
197 timeprofile_display(tag_detector_->tp);
198
199 VLOG(1) << "Took "
200 << std::chrono::duration<double>(end_time - start_time).count()
201 << " seconds to detect overall";
202
203 return results;
204}
205
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800206} // namespace vision
207} // namespace y2023