blob: bb74266d570bf2b88d3dbabf77c657cd3030d0f1 [file] [log] [blame]
Maxwell Henderson123c8172024-03-01 22:54:16 -08001#include <string>
2
3#include "Eigen/Dense"
4#include "opencv2/aruco.hpp"
5#include "opencv2/calib3d.hpp"
6#include "opencv2/core/eigen.hpp"
7#include "opencv2/features2d.hpp"
8#include "opencv2/highgui.hpp"
9#include "opencv2/highgui/highgui.hpp"
10#include "opencv2/imgproc.hpp"
11
12#include "aos/configuration.h"
13#include "aos/events/logging/log_reader.h"
14#include "aos/events/simulated_event_loop.h"
15#include "aos/init.h"
16#include "aos/util/mcap_logger.h"
17#include "frc971/constants/constants_sender_lib.h"
18#include "frc971/control_loops/pose.h"
19#include "frc971/vision/calibration_generated.h"
20#include "frc971/vision/charuco_lib.h"
21#include "frc971/vision/target_mapper.h"
22#include "frc971/vision/vision_util_lib.h"
23#include "frc971/vision/visualize_robot.h"
24#include "y2024/constants/simulated_constants_sender.h"
25#include "y2024/vision/vision_util.h"
26
27DEFINE_string(config, "",
28 "If set, override the log's config file with this one.");
29DEFINE_string(constants_path, "y2024/constants/constants.json",
30 "Path to the constant file");
31DEFINE_string(dump_constraints_to, "/tmp/mapping_constraints.txt",
32 "Write the target constraints to this path");
33DEFINE_string(dump_stats_to, "/tmp/mapping_stats.txt",
34 "Write the mapping stats to this path");
35DEFINE_string(field_name, "charged_up",
36 "Field name, for the output json filename and flatbuffer field");
37DEFINE_string(json_path, "y2024/vision/maps/target_map.json",
38 "Specify path for json with initial pose guesses.");
39DEFINE_double(max_pose_error, 1e-6,
40 "Throw out target poses with a higher pose error than this");
41DEFINE_double(
42 max_pose_error_ratio, 0.4,
43 "Throw out target poses with a higher pose error ratio than this");
44DEFINE_string(mcap_output_path, "", "Log to output.");
45DEFINE_string(output_dir, "y2024/vision/maps",
46 "Directory to write solved target map to");
47DEFINE_double(pause_on_distance, 5.0,
48 "Pause if two consecutive implied robot positions differ by more "
49 "than this many meters");
50DEFINE_string(orin, "orin1",
51 "Orin name to generate mcap log for; defaults to pi1.");
52DEFINE_uint64(skip_to, 1,
53 "Start at combined image of this number (1 is the first image)");
54DEFINE_bool(solve, true, "Whether to solve for the field's target map.");
55DEFINE_int32(team_number, 0,
56 "Required: Use the calibration for a node with this team number");
57DEFINE_uint64(wait_key, 1,
58 "Time in ms to wait between images, if no click (0 to wait "
59 "indefinitely until click).");
60
61DECLARE_int32(frozen_target_id);
62DECLARE_int32(min_target_id);
63DECLARE_int32(max_target_id);
64DECLARE_bool(visualize_solver);
65
66namespace y2024::vision {
67using frc971::vision::DataAdapter;
68using frc971::vision::ImageCallback;
69using frc971::vision::PoseUtils;
70using frc971::vision::TargetMap;
71using frc971::vision::TargetMapper;
72using frc971::vision::VisualizeRobot;
73namespace calibration = frc971::vision::calibration;
74
75// Class to handle reading target poses from a replayed log,
76// displaying various debug info, and passing the poses to
77// frc971::vision::TargetMapper for field mapping.
78class TargetMapperReplay {
79 public:
80 TargetMapperReplay(aos::logger::LogReader *reader);
81
82 // Solves for the target poses with the accumulated detections if FLAGS_solve.
83 void MaybeSolve();
84
85 private:
86 static constexpr int kImageWidth = 1280;
87 // Map from pi node name to color for drawing
88 static const std::map<std::string, cv::Scalar> kOrinColors;
89 // Contains fixed target poses without solving, for use with visualization
90 static const TargetMapper kFixedTargetMapper;
91
92 // Change reference frame from camera to robot
93 static Eigen::Affine3d CameraToRobotDetection(Eigen::Affine3d H_camera_target,
94 Eigen::Affine3d extrinsics);
95
96 // Adds april tag detections into the detection list, and handles
97 // visualization
98 void HandleAprilTags(const TargetMap &map,
99 aos::distributed_clock::time_point node_distributed_time,
100 std::string camera_name, Eigen::Affine3d extrinsics);
101
102 // Gets images from the given pi and passes apriltag positions to
103 // HandleAprilTags()
104 void HandleNodeCaptures(
105 aos::EventLoop *mapping_event_loop,
106 frc971::constants::ConstantsFetcher<y2024::Constants> *constants_fetcher,
107 int camera_number);
108
109 aos::logger::LogReader *reader_;
110 // April tag detections from all pis
111 std::vector<DataAdapter::TimestampedDetection> timestamped_target_detections_;
112
113 VisualizeRobot vis_robot_;
114 // Set of node names which are currently drawn on the display
115 std::set<std::string> drawn_nodes_;
116 // Number of frames displayed
117 size_t display_count_;
118 // Last time we drew onto the display image.
119 // This is different from when we actually call imshow() to update
120 // the display window
121 aos::distributed_clock::time_point last_draw_time_;
122
123 Eigen::Affine3d last_H_world_robot_;
124 // Maximum distance between consecutive T_world_robot's in one display frame,
125 // used to determine if we need to pause for the user to see this frame
126 // clearly
127 double max_delta_T_world_robot_;
128
129 std::vector<std::unique_ptr<aos::EventLoop>> mapping_event_loops_;
130
131 std::unique_ptr<aos::EventLoop> mcap_event_loop_;
132 std::unique_ptr<aos::McapLogger> relogger_;
133};
134
135const auto TargetMapperReplay::kOrinColors = std::map<std::string, cv::Scalar>{
136 {"/orin1/camera0", cv::Scalar(255, 0, 255)},
137 {"/orin1/camera1", cv::Scalar(255, 255, 0)},
138 {"/imu/camera0", cv::Scalar(0, 255, 255)},
139 {"/imu/camera1", cv::Scalar(255, 165, 0)},
140};
141
142const auto TargetMapperReplay::kFixedTargetMapper =
143 TargetMapper(FLAGS_json_path, ceres::examples::VectorOfConstraints{});
144
145Eigen::Affine3d TargetMapperReplay::CameraToRobotDetection(
146 Eigen::Affine3d H_camera_target, Eigen::Affine3d extrinsics) {
147 const Eigen::Affine3d H_robot_camera = extrinsics;
148 const Eigen::Affine3d H_robot_target = H_robot_camera * H_camera_target;
149 return H_robot_target;
150}
151
152TargetMapperReplay::TargetMapperReplay(aos::logger::LogReader *reader)
153 : reader_(reader),
154 timestamped_target_detections_(),
155 vis_robot_(cv::Size(1280, 1000)),
156 drawn_nodes_(),
157 display_count_(0),
158 last_draw_time_(aos::distributed_clock::min_time),
159 last_H_world_robot_(Eigen::Matrix4d::Identity()),
160 max_delta_T_world_robot_(0.0) {
161 reader_->RemapLoggedChannel("/orin1/constants", "y2024.Constants");
162 reader_->RemapLoggedChannel("/imu/constants", "y2024.Constants");
163 reader_->Register();
164
165 SendSimulationConstants(reader_->event_loop_factory(), FLAGS_team_number,
166 FLAGS_constants_path);
167
168 std::vector<std::string> node_list;
169 node_list.push_back("imu");
170 node_list.push_back("orin1");
171
172 for (std::string node : node_list) {
173 const aos::Node *pi =
174 aos::configuration::GetNode(reader->configuration(), node);
175
176 mapping_event_loops_.emplace_back(
177 reader_->event_loop_factory()->MakeEventLoop(node + "_mapping_camera0",
178 pi));
179 mapping_event_loops_.emplace_back(
180 reader_->event_loop_factory()->MakeEventLoop(node + "_mapping_camera1",
181 pi));
182 frc971::constants::ConstantsFetcher<y2024::Constants> constants_fetcher(
183 mapping_event_loops_[mapping_event_loops_.size() - 1].get());
184 HandleNodeCaptures(
185 mapping_event_loops_[mapping_event_loops_.size() - 2].get(),
186 &constants_fetcher, 0);
187 HandleNodeCaptures(
188 mapping_event_loops_[mapping_event_loops_.size() - 1].get(),
189 &constants_fetcher, 1);
190 }
191
192 if (FLAGS_visualize_solver) {
193 vis_robot_.ClearImage();
194 const double kFocalLength = 500.0;
195 vis_robot_.SetDefaultViewpoint(kImageWidth, kFocalLength);
196 }
197}
198
199// Add detected apriltag poses relative to the robot to
200// timestamped_target_detections
201void TargetMapperReplay::HandleAprilTags(
202 const TargetMap &map,
203 aos::distributed_clock::time_point node_distributed_time,
204 std::string camera_name, Eigen::Affine3d extrinsics) {
205 bool drew = false;
206 std::stringstream label;
207 label << camera_name << " - ";
208
209 for (const auto *target_pose_fbs : *map.target_poses()) {
210 // Skip detections with invalid ids
211 if (static_cast<TargetMapper::TargetId>(target_pose_fbs->id()) <
212 FLAGS_min_target_id ||
213 static_cast<TargetMapper::TargetId>(target_pose_fbs->id()) >
214 FLAGS_max_target_id) {
215 VLOG(1) << "Skipping tag with invalid id of " << target_pose_fbs->id();
216 continue;
217 }
218
219 // Skip detections with high pose errors
220 if (target_pose_fbs->pose_error() > FLAGS_max_pose_error) {
221 VLOG(1) << "Skipping tag " << target_pose_fbs->id()
222 << " due to pose error of " << target_pose_fbs->pose_error();
223 continue;
224 }
225 // Skip detections with high pose error ratios
226 if (target_pose_fbs->pose_error_ratio() > FLAGS_max_pose_error_ratio) {
227 VLOG(1) << "Skipping tag " << target_pose_fbs->id()
228 << " due to pose error ratio of "
229 << target_pose_fbs->pose_error_ratio();
230 continue;
231 }
232
233 const TargetMapper::TargetPose target_pose =
234 PoseUtils::TargetPoseFromFbs(*target_pose_fbs);
235
236 Eigen::Affine3d H_camera_target =
237 Eigen::Translation3d(target_pose.pose.p) * target_pose.pose.q;
238 Eigen::Affine3d H_robot_target =
239 CameraToRobotDetection(H_camera_target, extrinsics);
240
241 ceres::examples::Pose3d target_pose_camera =
242 PoseUtils::Affine3dToPose3d(H_camera_target);
243 double distance_from_camera = target_pose_camera.p.norm();
244 double distortion_factor = target_pose_fbs->distortion_factor();
245
246 if (distance_from_camera > 5.0) {
247 continue;
248 }
249
250 CHECK(map.has_monotonic_timestamp_ns())
251 << "Need detection timestamps for mapping";
252
253 timestamped_target_detections_.emplace_back(
254 DataAdapter::TimestampedDetection{
255 .time = node_distributed_time,
256 .H_robot_target = H_robot_target,
257 .distance_from_camera = distance_from_camera,
258 .distortion_factor = distortion_factor,
259 .id = static_cast<TargetMapper::TargetId>(target_pose.id)});
260
261 if (FLAGS_visualize_solver) {
262 // If we've already drawn this camera_name in the current image,
263 // display the image before clearing and adding the new poses
264 if (drawn_nodes_.count(camera_name) != 0) {
265 display_count_++;
266 cv::putText(vis_robot_.image_,
267 "Poses #" + std::to_string(display_count_),
268 cv::Point(600, 10), cv::FONT_HERSHEY_PLAIN, 1.0,
269 cv::Scalar(255, 255, 255));
270
271 if (display_count_ >= FLAGS_skip_to) {
272 VLOG(1) << "Showing image for node " << camera_name
273 << " since we've drawn it already";
274 cv::imshow("View", vis_robot_.image_);
275 // Pause if delta_T is too large, but only after first image (to make
276 // sure the delta's are correct
277 if (max_delta_T_world_robot_ > FLAGS_pause_on_distance &&
278 display_count_ > 1) {
279 LOG(INFO) << "Pausing since the delta between robot estimates is "
280 << max_delta_T_world_robot_ << " which is > threshold of "
281 << FLAGS_pause_on_distance;
282 cv::waitKey(0);
283 } else {
284 cv::waitKey(FLAGS_wait_key);
285 }
286 max_delta_T_world_robot_ = 0.0;
287 } else {
288 VLOG(1) << "At poses #" << std::to_string(display_count_);
289 }
290 vis_robot_.ClearImage();
291 drawn_nodes_.clear();
292 }
293
294 Eigen::Affine3d H_world_target = PoseUtils::Pose3dToAffine3d(
295 kFixedTargetMapper.GetTargetPoseById(target_pose_fbs->id())->pose);
296 Eigen::Affine3d H_world_robot = H_world_target * H_robot_target.inverse();
297 VLOG(2) << camera_name << ", id " << target_pose_fbs->id()
298 << ", t = " << node_distributed_time
299 << ", pose_error = " << target_pose_fbs->pose_error()
300 << ", pose_error_ratio = " << target_pose_fbs->pose_error_ratio()
301 << ", robot_pos (x,y,z) = "
302 << H_world_robot.translation().transpose();
303
304 label << "id " << target_pose_fbs->id() << ": err (% of max): "
305 << (target_pose_fbs->pose_error() / FLAGS_max_pose_error)
306 << " err_ratio: " << target_pose_fbs->pose_error_ratio() << " ";
307
308 vis_robot_.DrawRobotOutline(H_world_robot, camera_name,
309 kOrinColors.at(camera_name));
310 vis_robot_.DrawFrameAxes(H_world_target,
311 std::to_string(target_pose_fbs->id()),
312 kOrinColors.at(camera_name));
313
314 double delta_T_world_robot =
315 (H_world_robot.translation() - last_H_world_robot_.translation())
316 .norm();
317 max_delta_T_world_robot_ =
318 std::max(delta_T_world_robot, max_delta_T_world_robot_);
319
320 VLOG(1) << "Drew in info for robot " << camera_name << " and target #"
321 << target_pose_fbs->id();
322 drew = true;
323 last_draw_time_ = node_distributed_time;
324 last_H_world_robot_ = H_world_robot;
325 }
326 }
327
328 if (FLAGS_visualize_solver) {
329 if (drew) {
330 // Collect all the labels from a given node, and add the text
331 size_t pi_number =
332 static_cast<size_t>(camera_name[camera_name.size() - 1] - '0');
333 cv::putText(vis_robot_.image_, label.str(),
334 cv::Point(10, 10 + 20 * pi_number), cv::FONT_HERSHEY_PLAIN,
335 1.0, kOrinColors.at(camera_name));
336
337 drawn_nodes_.emplace(camera_name);
338 } else if (node_distributed_time - last_draw_time_ >
339 std::chrono::milliseconds(30) &&
340 display_count_ >= FLAGS_skip_to) {
341 cv::putText(vis_robot_.image_, "No detections", cv::Point(10, 0),
342 cv::FONT_HERSHEY_PLAIN, 1.0, kOrinColors.at(camera_name));
343 // Display and clear the image if we haven't draw in a while
344 VLOG(1) << "Displaying image due to time lapse";
345 cv::imshow("View", vis_robot_.image_);
346 cv::waitKey(FLAGS_wait_key);
347 vis_robot_.ClearImage();
348 max_delta_T_world_robot_ = 0.0;
349 drawn_nodes_.clear();
350 }
351 }
352}
353
354void TargetMapperReplay::HandleNodeCaptures(
355 aos::EventLoop *mapping_event_loop,
356 frc971::constants::ConstantsFetcher<y2024::Constants> *constants_fetcher,
357 int camera_number) {
358 // Get the camera extrinsics
359 const auto *calibration = FindCameraCalibration(
360 constants_fetcher->constants(),
361 mapping_event_loop->node()->name()->string_view(), camera_number);
362 cv::Mat extrinsics_cv = frc971::vision::CameraExtrinsics(calibration).value();
363 Eigen::Matrix4d extrinsics_matrix;
364 cv::cv2eigen(extrinsics_cv, extrinsics_matrix);
365 const auto extrinsics = Eigen::Affine3d(extrinsics_matrix);
366 std::string camera_name = absl::StrFormat(
367 "/%s/camera%d", mapping_event_loop->node()->name()->str(), camera_number);
368
369 mapping_event_loop->MakeWatcher(
370 camera_name.c_str(), [this, mapping_event_loop, extrinsics,
371 camera_name](const TargetMap &map) {
372 aos::distributed_clock::time_point node_distributed_time =
373 reader_->event_loop_factory()
374 ->GetNodeEventLoopFactory(mapping_event_loop->node())
375 ->ToDistributedClock(aos::monotonic_clock::time_point(
376 aos::monotonic_clock::duration(
377 map.monotonic_timestamp_ns())));
378
379 HandleAprilTags(map, node_distributed_time, camera_name, extrinsics);
380 });
381}
382
383void TargetMapperReplay::MaybeSolve() {
384 if (FLAGS_solve) {
385 auto target_constraints =
386 DataAdapter::MatchTargetDetections(timestamped_target_detections_);
387
388 // Remove constraints between the two sides of the field - these are
389 // basically garbage because of how far the camera is. We will use seeding
390 // below to connect the two sides
391 target_constraints.erase(
392 std::remove_if(target_constraints.begin(), target_constraints.end(),
393 [](const auto &constraint) {
394 constexpr TargetMapper::TargetId kMaxRedId = 4;
395 TargetMapper::TargetId min_id =
396 std::min(constraint.id_begin, constraint.id_end);
397 TargetMapper::TargetId max_id =
398 std::max(constraint.id_begin, constraint.id_end);
399 return (min_id <= kMaxRedId && max_id > kMaxRedId);
400 }),
401 target_constraints.end());
402
403 LOG(INFO) << "Solving for locations of tags with "
404 << target_constraints.size() << " constraints";
405 TargetMapper mapper(FLAGS_json_path, target_constraints);
406 mapper.Solve(FLAGS_field_name, FLAGS_output_dir);
407
408 if (!FLAGS_dump_constraints_to.empty()) {
409 mapper.DumpConstraints(FLAGS_dump_constraints_to);
410 }
411 if (!FLAGS_dump_stats_to.empty()) {
412 mapper.DumpStats(FLAGS_dump_stats_to);
413 }
414 }
415}
416
417void MappingMain(int argc, char *argv[]) {
418 std::vector<DataAdapter::TimestampedDetection> timestamped_target_detections;
419
420 std::optional<aos::FlatbufferDetachedBuffer<aos::Configuration>> config =
421 (FLAGS_config.empty()
422 ? std::nullopt
423 : std::make_optional(aos::configuration::ReadConfig(FLAGS_config)));
424
425 // Open logfiles
426 aos::logger::LogReader reader(
427 aos::logger::SortParts(aos::logger::FindLogs(argc, argv)),
428 config.has_value() ? &config->message() : nullptr);
429
430 TargetMapperReplay mapper_replay(&reader);
431 reader.event_loop_factory()->Run();
432 mapper_replay.MaybeSolve();
433}
434
435} // namespace y2024::vision
436
437int main(int argc, char **argv) {
438 aos::InitGoogle(&argc, &argv);
439 y2024::vision::MappingMain(argc, argv);
440}