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