blob: cb6a5bc74fb224666671c0258d2cffb61e56106c [file] [log] [blame]
Maxwell Hendersonfebee252023-01-28 16:53:52 -08001#include "y2023/vision/aprilrobotics.h"
2
James Kuszmauld67f6d22023-02-05 17:37:25 -08003#include "y2023/vision/vision_util.h"
4
Maxwell Hendersonfebee252023-01-28 16:53:52 -08005DEFINE_bool(
6 debug, false,
7 "If true, dump a ton of debug and crash on the first valid detection.");
8
Maxwell Hendersonfebee252023-01-28 16:53:52 -08009namespace 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)
James Kuszmauld67f6d22023-02-05 17:37:25 -080016 : calibration_data_(event_loop),
Maxwell Hendersonfebee252023-01-28 16:53:52 -080017 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
James Kuszmauld67f6d22023-02-05 17:37:25 -080041 calibration_ = FindCameraCalibration(
42 calibration_data_.constants(), event_loop->node()->name()->string_view());
Maxwell Hendersonfebee252023-01-28 16:53:52 -080043 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
Yash Chainani728ae222023-02-04 19:48:12 -0800123 std::vector<flatbuffers::Offset<AprilCorners>> corners_vector;
124
125 auto builder = april_debug_sender_.MakeBuilder();
126
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800127 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";
Yash Chainani728ae222023-02-04 19:48:12 -0800162
163 std::vector<Point> corner_points;
164
165 corner_points.emplace_back(det->p[0][0], det->p[0][1]);
166 corner_points.emplace_back(det->p[1][0], det->p[1][1]);
167 corner_points.emplace_back(det->p[2][0], det->p[2][1]);
168 corner_points.emplace_back(det->p[3][0], det->p[3][1]);
169
170 auto corner_points_fbs =
171 builder.fbb()->CreateVectorOfStructs(corner_points);
172
173 AprilCorners::Builder april_corners_builder =
174 builder.MakeBuilder<AprilCorners>();
175
176 april_corners_builder.add_id(det->id);
177 april_corners_builder.add_points(corner_points_fbs);
178
179 corners_vector.emplace_back(april_corners_builder.Finish());
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800180 }
181 }
182
Yash Chainani728ae222023-02-04 19:48:12 -0800183 auto corners_vector_fbs = builder.fbb()->CreateVector(corners_vector);
184
185 AprilDebug::Builder april_debug_builder = builder.MakeBuilder<AprilDebug>();
186
187 april_debug_builder.add_corners(corners_vector_fbs);
188
189 builder.CheckOk(builder.Send(april_debug_builder.Finish()));
190
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800191 apriltag_detections_destroy(detections);
192
193 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
194
195 timeprofile_display(tag_detector_->tp);
196
Austin Schuhd2667932023-02-04 16:22:39 -0800197 VLOG(1) << "Took " << chrono::duration<double>(end_time - start_time).count()
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800198 << " seconds to detect overall";
199
200 return results;
201}
202
Maxwell Hendersonfebee252023-01-28 16:53:52 -0800203} // namespace vision
204} // namespace y2023