blob: cbfd3f6974eeaba04abd98380532de51eaf3f283 [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_(
26 event_loop->MakeSender<frc971::vision::TargetMap>("/camera")) {
27 tag_family_ = tag16h5_create();
28 tag_detector_ = apriltag_detector_create();
29
30 apriltag_detector_add_family_bits(tag_detector_, tag_family_, 1);
31 tag_detector_->nthreads = 6;
32 tag_detector_->wp = workerpool_create(tag_detector_->nthreads);
33 tag_detector_->qtp.min_white_black_diff = 5;
34 tag_detector_->debug = FLAGS_debug;
35
36 std::string hostname = aos::network::GetHostname();
37
38 // Check team string is valid
39 std::optional<uint16_t> pi_number = aos::network::ParsePiNumber(hostname);
40 std::optional<uint16_t> team_number =
41 aos::network::team_number_internal::ParsePiTeamNumber(hostname);
42 CHECK(pi_number) << "Unable to parse pi number from '" << hostname << "'";
43 CHECK(team_number);
44
45 calibration_ = FindCameraCalibration(&calibration_data_.message(),
46 "pi" + std::to_string(*pi_number));
47 intrinsics_ = CameraIntrinsics(calibration_);
48 camera_distortion_coeffs_ = CameraDistCoeffs(calibration_);
49
50 image_callback_.set_format(frc971::vision::ImageCallback::Format::GRAYSCALE);
51}
52
53AprilRoboticsDetector::~AprilRoboticsDetector() {
54 apriltag_detector_destroy(tag_detector_);
55 free(tag_family_);
56}
57
58void AprilRoboticsDetector::SetWorkerpoolAffinities() {
59 for (int i = 0; i < tag_detector_->wp->nthreads; i++) {
60 cpu_set_t affinity;
61 CPU_ZERO(&affinity);
62 CPU_SET(i, &affinity);
63 pthread_setaffinity_np(tag_detector_->wp->threads[i], sizeof(affinity),
64 &affinity);
65 struct sched_param param;
66 param.sched_priority = 20;
67 int res = pthread_setschedparam(tag_detector_->wp->threads[i], SCHED_FIFO,
68 &param);
69 PCHECK(res == 0) << "Failed to set priority of threadpool threads";
70 }
71}
72
milind-u09fb1252023-01-28 19:21:41 -080073void AprilRoboticsDetector::HandleImage(cv::Mat image_color_mat,
74 aos::monotonic_clock::time_point eof) {
Maxwell Hendersonfebee252023-01-28 16:53:52 -080075 std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>> detections =
76 DetectTags(image_color_mat);
77
78 auto builder = target_map_sender_.MakeBuilder();
79 std::vector<flatbuffers::Offset<frc971::vision::TargetPoseFbs>> target_poses;
80 for (const auto &[detection, pose] : detections) {
81 target_poses.emplace_back(
82 BuildTargetPose(pose, detection.id, builder.fbb()));
83 }
84 const auto target_poses_offset = builder.fbb()->CreateVector(target_poses);
85 auto target_map_builder = builder.MakeBuilder<frc971::vision::TargetMap>();
Maxwell Hendersonfebee252023-01-28 16:53:52 -080086 target_map_builder.add_target_poses(target_poses_offset);
milind-u09fb1252023-01-28 19:21:41 -080087 target_map_builder.add_monotonic_timestamp_ns(eof.time_since_epoch().count());
Maxwell Hendersonfebee252023-01-28 16:53:52 -080088 builder.CheckOk(builder.Send(target_map_builder.Finish()));
89}
90
91flatbuffers::Offset<frc971::vision::TargetPoseFbs>
92AprilRoboticsDetector::BuildTargetPose(
93 const apriltag_pose_t &pose,
94 frc971::vision::TargetMapper::TargetId target_id,
95 flatbuffers::FlatBufferBuilder *fbb) {
96 const auto T =
97 Eigen::Translation3d(pose.t->data[0], pose.t->data[1], pose.t->data[2]);
milind-u3f5f83c2023-01-29 15:23:51 -080098 const auto position_offset =
99 frc971::vision::CreatePosition(*fbb, T.x(), T.y(), T.z());
100
101 const auto orientation = Eigen::Quaterniond(Eigen::Matrix3d(pose.R->data));
102 const auto orientation_offset = frc971::vision::CreateQuaternion(
103 *fbb, orientation.w(), orientation.x(), orientation.y(), orientation.z());
104
105 return frc971::vision::CreateTargetPoseFbs(*fbb, target_id, position_offset,
106 orientation_offset);
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800107}
108
109std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>>
110AprilRoboticsDetector::DetectTags(cv::Mat image) {
111 const aos::monotonic_clock::time_point start_time =
112 aos::monotonic_clock::now();
113
114 image_u8_t im = {
milind-u09fb1252023-01-28 19:21:41 -0800115 .width = image.cols,
116 .height = image.rows,
117 .stride = image.cols,
118 .buf = image.data,
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800119 };
120
121 ftrace_.FormatMessage("Starting detect\n");
122 zarray_t *detections = apriltag_detector_detect(tag_detector_, &im);
123 ftrace_.FormatMessage("Done detecting\n");
124
125 std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>> results;
126
127 for (int i = 0; i < zarray_size(detections); i++) {
128 apriltag_detection_t *det;
129 zarray_get(detections, i, &det);
130
131 if (det->decision_margin > 30) {
132 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
133 << " margin: " << det->decision_margin;
134
135 const aos::monotonic_clock::time_point before_pose_estimation =
136 aos::monotonic_clock::now();
137 // First create an apriltag_detection_info_t struct using your known
138 // parameters.
139 apriltag_detection_info_t info;
140 info.det = det;
141 info.tagsize = 0.1524;
142 info.fx = intrinsics_.at<double>(0, 0);
143 info.fy = intrinsics_.at<double>(1, 1);
144 info.cx = intrinsics_.at<double>(0, 2);
145 info.cy = intrinsics_.at<double>(1, 2);
146
147 apriltag_pose_t pose;
148 double err = estimate_tag_pose(&info, &pose);
149
150 VLOG(1) << "err: " << err;
151
152 results.emplace_back(*det, pose);
153
154 const aos::monotonic_clock::time_point after_pose_estimation =
155 aos::monotonic_clock::now();
156
157 VLOG(1) << "Took "
Austin Schuhd2667932023-02-04 16:22:39 -0800158 << chrono::duration<double>(after_pose_estimation -
159 before_pose_estimation)
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800160 .count()
161 << " seconds for pose estimation";
162 }
163 }
164
165 apriltag_detections_destroy(detections);
166
167 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
168
169 timeprofile_display(tag_detector_->tp);
170
Austin Schuhd2667932023-02-04 16:22:39 -0800171 VLOG(1) << "Took " << chrono::duration<double>(end_time - start_time).count()
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800172 << " seconds to detect overall";
173
174 return results;
175}
176
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800177} // namespace vision
178} // namespace y2023