blob: fc9d7998d131f339ecfc3b6c534f167c54c6a486 [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]);
94 const auto rpy = frc971::vision::PoseUtils::RotationMatrixToEulerAngles(
95 Eigen::Matrix3d(pose.R->data));
96 return frc971::vision::CreateTargetPoseFbs(*fbb, target_id, T.x(), T.y(),
97 T.z(), rpy(0), rpy(1), rpy(2));
98}
99
100std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>>
101AprilRoboticsDetector::DetectTags(cv::Mat image) {
102 const aos::monotonic_clock::time_point start_time =
103 aos::monotonic_clock::now();
104
105 image_u8_t im = {
milind-u09fb1252023-01-28 19:21:41 -0800106 .width = image.cols,
107 .height = image.rows,
108 .stride = image.cols,
109 .buf = image.data,
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800110 };
111
112 ftrace_.FormatMessage("Starting detect\n");
113 zarray_t *detections = apriltag_detector_detect(tag_detector_, &im);
114 ftrace_.FormatMessage("Done detecting\n");
115
116 std::vector<std::pair<apriltag_detection_t, apriltag_pose_t>> results;
117
118 for (int i = 0; i < zarray_size(detections); i++) {
119 apriltag_detection_t *det;
120 zarray_get(detections, i, &det);
121
122 if (det->decision_margin > 30) {
123 VLOG(1) << "Found tag number " << det->id << " hamming: " << det->hamming
124 << " margin: " << det->decision_margin;
125
126 const aos::monotonic_clock::time_point before_pose_estimation =
127 aos::monotonic_clock::now();
128 // First create an apriltag_detection_info_t struct using your known
129 // parameters.
130 apriltag_detection_info_t info;
131 info.det = det;
132 info.tagsize = 0.1524;
133 info.fx = intrinsics_.at<double>(0, 0);
134 info.fy = intrinsics_.at<double>(1, 1);
135 info.cx = intrinsics_.at<double>(0, 2);
136 info.cy = intrinsics_.at<double>(1, 2);
137
138 apriltag_pose_t pose;
139 double err = estimate_tag_pose(&info, &pose);
140
141 VLOG(1) << "err: " << err;
142
143 results.emplace_back(*det, pose);
144
145 const aos::monotonic_clock::time_point after_pose_estimation =
146 aos::monotonic_clock::now();
147
148 VLOG(1) << "Took "
149 << std::chrono::duration<double>(after_pose_estimation -
150 before_pose_estimation)
151 .count()
152 << " seconds for pose estimation";
153 }
154 }
155
156 apriltag_detections_destroy(detections);
157
158 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
159
160 timeprofile_display(tag_detector_->tp);
161
162 VLOG(1) << "Took "
163 << std::chrono::duration<double>(end_time - start_time).count()
164 << " seconds to detect overall";
165
166 return results;
167}
168
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800169} // namespace vision
170} // namespace y2023