blob: 2b10798ad2aac473f85f3b75ae309ec2b5906324 [file] [log] [blame]
Yash Chainanid5c7f0d2022-11-19 17:05:57 -08001#include "aos/events/logging/log_reader.h"
2#include "aos/events/simulated_event_loop.h"
3#include "aos/init.h"
4#include "frc971/control_loops/pose.h"
5#include "frc971/vision/charuco_lib.h"
6#include "frc971/vision/target_mapper.h"
7#include "opencv2/aruco.hpp"
8#include "opencv2/calib3d.hpp"
9#include "opencv2/core/eigen.hpp"
10#include "opencv2/features2d.hpp"
11#include "opencv2/highgui.hpp"
12#include "opencv2/highgui/highgui.hpp"
13#include "opencv2/imgproc.hpp"
14#include "y2022/control_loops/superstructure/superstructure_status_generated.h"
15#include "y2022/vision/camera_reader.h"
16
17DEFINE_string(json_path, "target_map.json",
18 "Specify path for json with initial pose guesses.");
Milind Upadhyay915d6002022-12-26 20:37:43 -080019DEFINE_int32(team_number, 971,
20 "Use the calibration for a node with this team number");
21
22DEFINE_bool(
23 use_robot_position, false,
24 "If true, use localizer output messages to get the robot position, and "
25 "superstructure status messages to get the turret angle, at the "
26 "times of target detections. Currently does not work reliably on the box "
27 "of pis.");
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080028
29namespace y2022 {
30namespace vision {
31using frc971::vision::DataAdapter;
32using frc971::vision::PoseUtils;
33using frc971::vision::TargetMapper;
34namespace superstructure = ::y2022::control_loops::superstructure;
35
36// Find transformation from camera to robot reference frame
37Eigen::Affine3d CameraTransform(Eigen::Affine3d fixed_extrinsics,
38 Eigen::Affine3d turret_extrinsics,
39 double turret_position) {
40 // Calculate the pose of the camera relative to the robot origin.
41 Eigen::Affine3d H_robot_camrob =
42 fixed_extrinsics *
43 Eigen::Affine3d(frc971::control_loops::TransformationMatrixForYaw<double>(
44 turret_position)) *
45 turret_extrinsics;
46
47 return H_robot_camrob;
48}
49
50// Change reference frame from camera to robot
51Eigen::Affine3d CameraToRobotDetection(Eigen::Affine3d H_camcv_target,
52 Eigen::Affine3d fixed_extrinsics,
53 Eigen::Affine3d turret_extrinsics,
54 double turret_position) {
55 // With X, Y, Z being robot axes and x, y, z being camera axes,
56 // x = -Y, y = -Z, z = X
57 const Eigen::Affine3d H_camcv_camrob =
58 Eigen::Affine3d((Eigen::Matrix4d() << 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, -1.0,
59 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)
60 .finished());
61
62 const Eigen::Affine3d H_robot_camrob =
63 CameraTransform(fixed_extrinsics, turret_extrinsics, turret_position);
64 const Eigen::Affine3d H_robot_target =
65 H_robot_camrob * H_camcv_camrob.inverse() * H_camcv_target;
66 return H_robot_target;
67}
68
69// Add detected apriltag poses relative to the robot to
70// timestamped_target_detections
Milind Upadhyay915d6002022-12-26 20:37:43 -080071void HandleAprilTag(aos::distributed_clock::time_point pi_distributed_time,
72 std::vector<cv::Vec4i> april_ids,
73 std::vector<Eigen::Vector3d> rvecs_eigen,
74 std::vector<Eigen::Vector3d> tvecs_eigen,
75 std::vector<DataAdapter::TimestampedDetection>
76 *timestamped_target_detections,
77 std::optional<aos::Fetcher<superstructure::Status>>
78 *superstructure_status_fetcher,
79 Eigen::Affine3d fixed_extrinsics,
80 Eigen::Affine3d turret_extrinsics) {
81 double turret_position = 0.0;
82
83 if (superstructure_status_fetcher->has_value()) {
84 CHECK(superstructure_status_fetcher->value().Fetch());
85 turret_position =
86 superstructure_status_fetcher->value().get()->turret()->position();
87 }
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080088
89 for (size_t tag = 0; tag < april_ids.size(); tag++) {
90 Eigen::Translation3d T_camera_target = Eigen::Translation3d(
91 tvecs_eigen[tag][0], tvecs_eigen[tag][1], tvecs_eigen[tag][2]);
92 Eigen::AngleAxisd r_angle = Eigen::AngleAxisd(
93 rvecs_eigen[tag].norm(), rvecs_eigen[tag] / rvecs_eigen[tag].norm());
94 CHECK(rvecs_eigen[tag].norm() != 0) << "rvecs norm = 0; divide by 0";
95 Eigen::Affine3d H_camcv_target = T_camera_target * r_angle;
96
97 Eigen::Affine3d H_robot_target = CameraToRobotDetection(
98 H_camcv_target, fixed_extrinsics, turret_extrinsics, turret_position);
99
100 timestamped_target_detections->emplace_back(
101 DataAdapter::TimestampedDetection{.time = pi_distributed_time,
102 .H_robot_target = H_robot_target,
103 .id = april_ids[tag][0]});
104 }
105}
106
107Eigen::Affine3d CameraFixedExtrinsics(
108 const calibration::CameraCalibration *camera_calibration) {
109 cv::Mat extrinsics(
110 4, 4, CV_32F,
111 const_cast<void *>(static_cast<const void *>(
112 camera_calibration->fixed_extrinsics()->data()->data())));
113 extrinsics.convertTo(extrinsics, CV_64F);
114 CHECK_EQ(extrinsics.total(),
115 camera_calibration->fixed_extrinsics()->data()->size());
116 Eigen::Matrix4d extrinsics_eigen;
117 cv::cv2eigen(extrinsics, extrinsics_eigen);
118 return Eigen::Affine3d(extrinsics_eigen);
119}
120
121Eigen::Affine3d CameraTurretExtrinsics(
122 const calibration::CameraCalibration *camera_calibration) {
123 cv::Mat extrinsics(
124 4, 4, CV_32F,
125 const_cast<void *>(static_cast<const void *>(
126 camera_calibration->turret_extrinsics()->data()->data())));
127 extrinsics.convertTo(extrinsics, CV_64F);
128 CHECK_EQ(extrinsics.total(),
129 camera_calibration->turret_extrinsics()->data()->size());
130 Eigen::Matrix4d extrinsics_eigen;
131 cv::cv2eigen(extrinsics, extrinsics_eigen);
132 return Eigen::Affine3d(extrinsics_eigen);
133}
134
135// Get images from pi and pass apriltag positions to HandleAprilTag()
136void HandlePiCaptures(
137 int pi_number, aos::EventLoop *pi_event_loop,
138 aos::logger::LogReader *reader,
Milind Upadhyay915d6002022-12-26 20:37:43 -0800139 std::optional<aos::Fetcher<superstructure::Status>>
140 *superstructure_status_fetcher,
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800141 std::vector<DataAdapter::TimestampedDetection>
142 *timestamped_target_detections,
143 std::vector<std::unique_ptr<CharucoExtractor>> *charuco_extractors,
144 std::vector<std::unique_ptr<ImageCallback>> *image_callbacks) {
145 const aos::FlatbufferSpan<calibration::CalibrationData> calibration_data(
146 CalibrationData());
147 const calibration::CameraCalibration *calibration =
148 CameraReader::FindCameraCalibration(&calibration_data.message(),
149 "pi" + std::to_string(pi_number),
150 FLAGS_team_number);
151 const auto turret_extrinsics = CameraTurretExtrinsics(calibration);
152 const auto fixed_extrinsics = CameraFixedExtrinsics(calibration);
153
154 charuco_extractors->emplace_back(std::make_unique<CharucoExtractor>(
155 pi_event_loop,
156 "pi-" + std::to_string(FLAGS_team_number) + "-" +
157 std::to_string(pi_number),
158 [=](cv::Mat /*rgb_image*/, aos::monotonic_clock::time_point eof,
159 std::vector<cv::Vec4i> april_ids,
160 std::vector<std::vector<cv::Point2f>> /*april_corners*/, bool valid,
161 std::vector<Eigen::Vector3d> rvecs_eigen,
162 std::vector<Eigen::Vector3d> tvecs_eigen) {
163 aos::distributed_clock::time_point pi_distributed_time =
164 reader->event_loop_factory()
165 ->GetNodeEventLoopFactory(pi_event_loop->node())
166 ->ToDistributedClock(eof);
167
168 if (valid) {
169 HandleAprilTag(pi_distributed_time, april_ids, rvecs_eigen,
170 tvecs_eigen, timestamped_target_detections,
171 superstructure_status_fetcher, fixed_extrinsics,
172 turret_extrinsics);
173 }
174 }));
175
176 std::string channel =
177 absl::StrCat("/pi", std::to_string(pi_number), "/camera");
178
179 image_callbacks->emplace_back(std::make_unique<ImageCallback>(
180 pi_event_loop, "/pi" + std::to_string(pi_number) + "/camera",
181 [&, charuco_extractor =
182 charuco_extractors->at(charuco_extractors->size() - 1).get()](
183 cv::Mat rgb_image, const aos::monotonic_clock::time_point eof) {
184 charuco_extractor->HandleImage(rgb_image, eof);
185 }));
186}
187
188void MappingMain(int argc, char *argv[]) {
189 std::vector<std::string> unsorted_logfiles =
190 aos::logger::FindLogs(argc, argv);
191
192 std::vector<DataAdapter::TimestampedPose> timestamped_robot_poses;
193 std::vector<DataAdapter::TimestampedDetection> timestamped_target_detections;
194
195 // open logfiles
196 aos::logger::LogReader reader(aos::logger::SortParts(unsorted_logfiles));
197 reader.Register();
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800198
Milind Upadhyay915d6002022-12-26 20:37:43 -0800199 std::optional<aos::Fetcher<superstructure::Status>>
200 superstructure_status_fetcher;
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800201
Milind Upadhyay915d6002022-12-26 20:37:43 -0800202 if (FLAGS_use_robot_position) {
203 const aos::Node *imu_node =
204 aos::configuration::GetNode(reader.configuration(), "imu");
205 std::unique_ptr<aos::EventLoop> imu_event_loop =
206 reader.event_loop_factory()->MakeEventLoop("imu", imu_node);
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800207
Milind Upadhyay915d6002022-12-26 20:37:43 -0800208 imu_event_loop->MakeWatcher(
209 "/localizer", [&](const frc971::controls::LocalizerOutput &localizer) {
210 aos::monotonic_clock::time_point imu_monotonic_time =
211 aos::monotonic_clock::time_point(aos::monotonic_clock::duration(
212 localizer.monotonic_timestamp_ns()));
213 aos::distributed_clock::time_point imu_distributed_time =
214 reader.event_loop_factory()
215 ->GetNodeEventLoopFactory(imu_node)
216 ->ToDistributedClock(imu_monotonic_time);
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800217
Milind Upadhyay915d6002022-12-26 20:37:43 -0800218 timestamped_robot_poses.emplace_back(DataAdapter::TimestampedPose{
219 .time = imu_distributed_time,
220 .pose =
221 ceres::examples::Pose2d{.x = localizer.x(),
222 .y = localizer.y(),
223 .yaw_radians = localizer.theta()}});
224 });
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800225
Milind Upadhyay915d6002022-12-26 20:37:43 -0800226 const aos::Node *roborio_node =
227 aos::configuration::GetNode(reader.configuration(), "roborio");
228 std::unique_ptr<aos::EventLoop> roborio_event_loop =
229 reader.event_loop_factory()->MakeEventLoop("roborio", roborio_node);
230
231 superstructure_status_fetcher =
232 roborio_event_loop->MakeFetcher<superstructure::Status>(
233 "/superstructure");
234 }
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800235
236 // Override target_type to AprilTag, since that's what we're using here
237 FLAGS_target_type = "april_tag";
238
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800239 std::vector<std::unique_ptr<CharucoExtractor>> charuco_extractors;
240 std::vector<std::unique_ptr<ImageCallback>> image_callbacks;
241
242 const aos::Node *pi1 =
243 aos::configuration::GetNode(reader.configuration(), "pi1");
244 std::unique_ptr<aos::EventLoop> pi1_event_loop =
245 reader.event_loop_factory()->MakeEventLoop("pi1", pi1);
246 HandlePiCaptures(
247 1, pi1_event_loop.get(), &reader, &superstructure_status_fetcher,
248 &timestamped_target_detections, &charuco_extractors, &image_callbacks);
249
250 const aos::Node *pi2 =
251 aos::configuration::GetNode(reader.configuration(), "pi2");
252 std::unique_ptr<aos::EventLoop> pi2_event_loop =
253 reader.event_loop_factory()->MakeEventLoop("pi2", pi2);
254 HandlePiCaptures(
255 2, pi2_event_loop.get(), &reader, &superstructure_status_fetcher,
256 &timestamped_target_detections, &charuco_extractors, &image_callbacks);
257
258 const aos::Node *pi3 =
259 aos::configuration::GetNode(reader.configuration(), "pi3");
260 std::unique_ptr<aos::EventLoop> pi3_event_loop =
261 reader.event_loop_factory()->MakeEventLoop("pi3", pi3);
262 HandlePiCaptures(
263 3, pi3_event_loop.get(), &reader, &superstructure_status_fetcher,
264 &timestamped_target_detections, &charuco_extractors, &image_callbacks);
265
266 const aos::Node *pi4 =
267 aos::configuration::GetNode(reader.configuration(), "pi4");
268 std::unique_ptr<aos::EventLoop> pi4_event_loop =
269 reader.event_loop_factory()->MakeEventLoop("pi4", pi4);
270 HandlePiCaptures(
271 4, pi4_event_loop.get(), &reader, &superstructure_status_fetcher,
272 &timestamped_target_detections, &charuco_extractors, &image_callbacks);
273
274 reader.event_loop_factory()->Run();
275
276 auto target_constraints =
Milind Upadhyay915d6002022-12-26 20:37:43 -0800277 (FLAGS_use_robot_position
278 ? DataAdapter::MatchTargetDetections(timestamped_robot_poses,
279 timestamped_target_detections)
280 .first
281 : DataAdapter::MatchTargetDetections(timestamped_target_detections));
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800282
283 frc971::vision::TargetMapper mapper(FLAGS_json_path, target_constraints);
Yash Chainani03669632022-12-17 19:37:34 -0800284 mapper.Solve("rapid_react");
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800285
286 // Pointers need to be deleted to destruct all fetchers
287 for (auto &charuco_extractor_ptr : charuco_extractors) {
288 charuco_extractor_ptr.reset();
289 }
290
291 for (auto &image_callback_ptr : image_callbacks) {
292 image_callback_ptr.reset();
293 }
294}
295
296} // namespace vision
297} // namespace y2022
298
299int main(int argc, char **argv) {
300 aos::InitGoogle(&argc, &argv);
301 y2022::vision::MappingMain(argc, argv);
Milind Upadhyay915d6002022-12-26 20:37:43 -0800302}