blob: f5fa34c68c8e95533ffcfb615f9b3f7a39c18e03 [file] [log] [blame]
Maxwell Henderson123c8172024-03-01 22:54:16 -08001#include <string>
2
3#include "Eigen/Dense"
Austin Schuh99f7c6a2024-06-25 22:07:44 -07004#include "absl/flags/flag.h"
Maxwell Henderson123c8172024-03-01 22:54:16 -08005#include "opencv2/aruco.hpp"
6#include "opencv2/calib3d.hpp"
7#include "opencv2/core/eigen.hpp"
8#include "opencv2/features2d.hpp"
9#include "opencv2/highgui.hpp"
10#include "opencv2/highgui/highgui.hpp"
11#include "opencv2/imgproc.hpp"
12
13#include "aos/configuration.h"
14#include "aos/events/logging/log_reader.h"
15#include "aos/events/simulated_event_loop.h"
16#include "aos/init.h"
17#include "aos/util/mcap_logger.h"
18#include "frc971/constants/constants_sender_lib.h"
19#include "frc971/control_loops/pose.h"
20#include "frc971/vision/calibration_generated.h"
21#include "frc971/vision/charuco_lib.h"
22#include "frc971/vision/target_mapper.h"
Jim Ostrowski67726282024-03-24 14:39:33 -070023#include "frc971/vision/vision_generated.h"
Maxwell Henderson123c8172024-03-01 22:54:16 -080024#include "frc971/vision/vision_util_lib.h"
25#include "frc971/vision/visualize_robot.h"
26#include "y2024/constants/simulated_constants_sender.h"
27#include "y2024/vision/vision_util.h"
28
Austin Schuh99f7c6a2024-06-25 22:07:44 -070029ABSL_FLAG(std::string, config, "",
30 "If set, override the log's config file with this one.");
31ABSL_FLAG(std::string, constants_path, "y2024/constants/constants.json",
32 "Path to the constant file");
33ABSL_FLAG(std::string, dump_constraints_to, "/tmp/mapping_constraints.txt",
34 "Write the target constraints to this path");
35ABSL_FLAG(std::string, dump_stats_to, "/tmp/mapping_stats.txt",
36 "Write the mapping stats to this path");
37ABSL_FLAG(std::string, field_name, "crescendo",
38 "Field name, for the output json filename and flatbuffer field");
39ABSL_FLAG(std::string, json_path, "y2024/vision/maps/target_map.json",
40 "Specify path for json with initial pose guesses.");
41ABSL_FLAG(double, max_pose_error, 1e-6,
42 "Throw out target poses with a higher pose error than this");
43ABSL_FLAG(double, max_pose_error_ratio, 0.4,
44 "Throw out target poses with a higher pose error ratio than this");
45ABSL_FLAG(std::string, mcap_output_path, "", "Log to output.");
46ABSL_FLAG(std::string, output_dir, "y2024/vision/maps",
47 "Directory to write solved target map to");
48ABSL_FLAG(double, pause_on_distance, 2.0,
49 "Pause if two consecutive implied robot positions differ by more "
50 "than this many meters");
51ABSL_FLAG(std::string, orin, "orin1",
52 "Orin name to generate mcap log for; defaults to orin1.");
53ABSL_FLAG(uint64_t, skip_to, 1,
54 "Start at combined image of this number (1 is the first image)");
55ABSL_FLAG(bool, solve, true, "Whether to solve for the field's target map.");
56ABSL_FLAG(bool, split_field, false,
57 "Whether to break solve into two sides of field");
58ABSL_FLAG(int32_t, team_number, 0,
59 "Required: Use the calibration for a node with this team number");
60ABSL_FLAG(uint64_t, wait_key, 1,
61 "Time in ms to wait between images, if no click (0 to wait "
62 "indefinitely until click).");
Maxwell Henderson123c8172024-03-01 22:54:16 -080063
Austin Schuh99f7c6a2024-06-25 22:07:44 -070064ABSL_DECLARE_FLAG(int32_t, frozen_target_id);
65ABSL_DECLARE_FLAG(int32_t, min_target_id);
66ABSL_DECLARE_FLAG(int32_t, max_target_id);
67ABSL_DECLARE_FLAG(bool, visualize_solver);
Maxwell Henderson123c8172024-03-01 22:54:16 -080068
69namespace y2024::vision {
70using frc971::vision::DataAdapter;
71using frc971::vision::ImageCallback;
72using frc971::vision::PoseUtils;
73using frc971::vision::TargetMap;
74using frc971::vision::TargetMapper;
75using frc971::vision::VisualizeRobot;
76namespace calibration = frc971::vision::calibration;
77
78// Class to handle reading target poses from a replayed log,
79// displaying various debug info, and passing the poses to
80// frc971::vision::TargetMapper for field mapping.
81class TargetMapperReplay {
82 public:
83 TargetMapperReplay(aos::logger::LogReader *reader);
84
85 // Solves for the target poses with the accumulated detections if FLAGS_solve.
86 void MaybeSolve();
87
88 private:
89 static constexpr int kImageWidth = 1280;
Jim Ostrowski67726282024-03-24 14:39:33 -070090
Maxwell Henderson123c8172024-03-01 22:54:16 -080091 // Contains fixed target poses without solving, for use with visualization
92 static const TargetMapper kFixedTargetMapper;
93
Jim Ostrowski5ff3c562024-03-20 20:35:11 -070094 // Map of TargetId to alliance "color" for splitting field
95 static std::map<uint, std::string> kIdAllianceMap;
96
Maxwell Henderson123c8172024-03-01 22:54:16 -080097 // Change reference frame from camera to robot
98 static Eigen::Affine3d CameraToRobotDetection(Eigen::Affine3d H_camera_target,
99 Eigen::Affine3d extrinsics);
100
101 // Adds april tag detections into the detection list, and handles
102 // visualization
103 void HandleAprilTags(const TargetMap &map,
104 aos::distributed_clock::time_point node_distributed_time,
105 std::string camera_name, Eigen::Affine3d extrinsics);
Maxwell Henderson123c8172024-03-01 22:54:16 -0800106 // Gets images from the given pi and passes apriltag positions to
107 // HandleAprilTags()
108 void HandleNodeCaptures(
109 aos::EventLoop *mapping_event_loop,
110 frc971::constants::ConstantsFetcher<y2024::Constants> *constants_fetcher,
111 int camera_number);
112
113 aos::logger::LogReader *reader_;
114 // April tag detections from all pis
115 std::vector<DataAdapter::TimestampedDetection> timestamped_target_detections_;
116
117 VisualizeRobot vis_robot_;
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700118 // Set of camera names which are currently drawn on the display
119 std::set<std::string> drawn_cameras_;
Maxwell Henderson123c8172024-03-01 22:54:16 -0800120 // Number of frames displayed
121 size_t display_count_;
122 // Last time we drew onto the display image.
123 // This is different from when we actually call imshow() to update
124 // the display window
125 aos::distributed_clock::time_point last_draw_time_;
126
127 Eigen::Affine3d last_H_world_robot_;
128 // Maximum distance between consecutive T_world_robot's in one display frame,
129 // used to determine if we need to pause for the user to see this frame
130 // clearly
131 double max_delta_T_world_robot_;
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700132 double ignore_count_;
133
Maxwell Henderson123c8172024-03-01 22:54:16 -0800134 std::vector<std::unique_ptr<aos::EventLoop>> mapping_event_loops_;
135
136 std::unique_ptr<aos::EventLoop> mcap_event_loop_;
137 std::unique_ptr<aos::McapLogger> relogger_;
138};
139
Jim Ostrowski67726282024-03-24 14:39:33 -0700140std::vector<CameraNode> node_list(y2024::vision::CreateNodeList());
141
142std::map<std::string, int> camera_ordering_map(
143 y2024::vision::CreateOrderingMap(node_list));
Maxwell Henderson123c8172024-03-01 22:54:16 -0800144
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700145std::map<uint, std::string> TargetMapperReplay::kIdAllianceMap = {
146 {1, "red"}, {2, "red"}, {3, "red"}, {4, "red"},
147 {5, "red"}, {6, "blue"}, {7, "blue"}, {8, "blue"},
148 {9, "blue"}, {10, "blue"}, {11, "red"}, {12, "red"},
149 {13, "red"}, {14, "blue"}, {15, "blue"}, {16, "blue"}};
150
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700151const auto TargetMapperReplay::kFixedTargetMapper = TargetMapper(
152 absl::GetFlag(FLAGS_json_path), ceres::examples::VectorOfConstraints{});
Maxwell Henderson123c8172024-03-01 22:54:16 -0800153
154Eigen::Affine3d TargetMapperReplay::CameraToRobotDetection(
155 Eigen::Affine3d H_camera_target, Eigen::Affine3d extrinsics) {
156 const Eigen::Affine3d H_robot_camera = extrinsics;
157 const Eigen::Affine3d H_robot_target = H_robot_camera * H_camera_target;
158 return H_robot_target;
159}
160
161TargetMapperReplay::TargetMapperReplay(aos::logger::LogReader *reader)
162 : reader_(reader),
163 timestamped_target_detections_(),
164 vis_robot_(cv::Size(1280, 1000)),
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700165 drawn_cameras_(),
Maxwell Henderson123c8172024-03-01 22:54:16 -0800166 display_count_(0),
167 last_draw_time_(aos::distributed_clock::min_time),
168 last_H_world_robot_(Eigen::Matrix4d::Identity()),
169 max_delta_T_world_robot_(0.0) {
170 reader_->RemapLoggedChannel("/orin1/constants", "y2024.Constants");
171 reader_->RemapLoggedChannel("/imu/constants", "y2024.Constants");
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700172 // If it's Box of Orins, don't remap roborio constants
James Kuszmaul9f5da5a2024-04-05 17:33:15 -0700173 reader_->MaybeRemapLoggedChannel<Constants>("/roborio/constants");
Maxwell Henderson123c8172024-03-01 22:54:16 -0800174 reader_->Register();
175
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700176 SendSimulationConstants(reader_->event_loop_factory(),
177 absl::GetFlag(FLAGS_team_number),
178 absl::GetFlag(FLAGS_constants_path));
Maxwell Henderson123c8172024-03-01 22:54:16 -0800179
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700180 if (absl::GetFlag(FLAGS_visualize_solver)) {
Jim Ostrowski67726282024-03-24 14:39:33 -0700181 vis_robot_.ClearImage();
182 // Set focal length to zoomed in, to view extrinsics
183 const double kFocalLength = 1500.0;
184 vis_robot_.SetDefaultViewpoint(kImageWidth, kFocalLength);
185 }
Maxwell Henderson123c8172024-03-01 22:54:16 -0800186
Jim Ostrowski67726282024-03-24 14:39:33 -0700187 for (const CameraNode &camera_node : node_list) {
188 const aos::Node *node = aos::configuration::GetNode(
189 reader_->configuration(), camera_node.node_name.c_str());
Maxwell Henderson123c8172024-03-01 22:54:16 -0800190
191 mapping_event_loops_.emplace_back(
Jim Ostrowski67726282024-03-24 14:39:33 -0700192 reader_->event_loop_factory()->MakeEventLoop(
193 camera_node.node_name + "mapping", node));
194
Maxwell Henderson123c8172024-03-01 22:54:16 -0800195 frc971::constants::ConstantsFetcher<y2024::Constants> constants_fetcher(
196 mapping_event_loops_[mapping_event_loops_.size() - 1].get());
197 HandleNodeCaptures(
Maxwell Henderson123c8172024-03-01 22:54:16 -0800198 mapping_event_loops_[mapping_event_loops_.size() - 1].get(),
Jim Ostrowski67726282024-03-24 14:39:33 -0700199 &constants_fetcher, camera_node.camera_number);
200
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700201 if (absl::GetFlag(FLAGS_visualize_solver)) {
Jim Ostrowski67726282024-03-24 14:39:33 -0700202 // Show the extrinsics calibration to start, for reference to confirm
203 const auto *calibration = FindCameraCalibration(
204 constants_fetcher.constants(),
205 mapping_event_loops_.back()->node()->name()->string_view(),
206 camera_node.camera_number);
207 cv::Mat extrinsics_cv =
208 frc971::vision::CameraExtrinsics(calibration).value();
209 Eigen::Matrix4d extrinsics_matrix;
210 cv::cv2eigen(extrinsics_cv, extrinsics_matrix);
211 const auto extrinsics = Eigen::Affine3d(extrinsics_matrix);
212
213 vis_robot_.DrawRobotOutline(extrinsics, camera_node.camera_name(),
214 kOrinColors.at(camera_node.camera_name()));
215 }
Maxwell Henderson123c8172024-03-01 22:54:16 -0800216 }
217
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700218 if (absl::GetFlag(FLAGS_visualize_solver)) {
Jim Ostrowski67726282024-03-24 14:39:33 -0700219 cv::imshow("Extrinsics", vis_robot_.image_);
220 cv::waitKey(0);
Maxwell Henderson123c8172024-03-01 22:54:16 -0800221 vis_robot_.ClearImage();
Jim Ostrowski67726282024-03-24 14:39:33 -0700222 // Reset focal length to more zoomed out view for field
Maxwell Henderson123c8172024-03-01 22:54:16 -0800223 const double kFocalLength = 500.0;
224 vis_robot_.SetDefaultViewpoint(kImageWidth, kFocalLength);
225 }
226}
227
228// Add detected apriltag poses relative to the robot to
229// timestamped_target_detections
230void TargetMapperReplay::HandleAprilTags(
231 const TargetMap &map,
232 aos::distributed_clock::time_point node_distributed_time,
233 std::string camera_name, Eigen::Affine3d extrinsics) {
234 bool drew = false;
235 std::stringstream label;
236 label << camera_name << " - ";
237
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700238 if (map.target_poses()->size() == 0) {
239 VLOG(2) << "Got 0 AprilTags for camera " << camera_name;
240 return;
241 }
242
Maxwell Henderson123c8172024-03-01 22:54:16 -0800243 for (const auto *target_pose_fbs : *map.target_poses()) {
244 // Skip detections with invalid ids
245 if (static_cast<TargetMapper::TargetId>(target_pose_fbs->id()) <
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700246 absl::GetFlag(FLAGS_min_target_id) ||
Maxwell Henderson123c8172024-03-01 22:54:16 -0800247 static_cast<TargetMapper::TargetId>(target_pose_fbs->id()) >
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700248 absl::GetFlag(FLAGS_max_target_id)) {
Maxwell Henderson123c8172024-03-01 22:54:16 -0800249 VLOG(1) << "Skipping tag with invalid id of " << target_pose_fbs->id();
250 continue;
251 }
252
253 // Skip detections with high pose errors
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700254 if (target_pose_fbs->pose_error() > absl::GetFlag(FLAGS_max_pose_error)) {
Maxwell Henderson123c8172024-03-01 22:54:16 -0800255 VLOG(1) << "Skipping tag " << target_pose_fbs->id()
256 << " due to pose error of " << target_pose_fbs->pose_error();
257 continue;
258 }
259 // Skip detections with high pose error ratios
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700260 if (target_pose_fbs->pose_error_ratio() >
261 absl::GetFlag(FLAGS_max_pose_error_ratio)) {
Maxwell Henderson123c8172024-03-01 22:54:16 -0800262 VLOG(1) << "Skipping tag " << target_pose_fbs->id()
263 << " due to pose error ratio of "
264 << target_pose_fbs->pose_error_ratio();
265 continue;
266 }
267
268 const TargetMapper::TargetPose target_pose =
269 PoseUtils::TargetPoseFromFbs(*target_pose_fbs);
270
271 Eigen::Affine3d H_camera_target =
272 Eigen::Translation3d(target_pose.pose.p) * target_pose.pose.q;
273 Eigen::Affine3d H_robot_target =
274 CameraToRobotDetection(H_camera_target, extrinsics);
275
276 ceres::examples::Pose3d target_pose_camera =
277 PoseUtils::Affine3dToPose3d(H_camera_target);
278 double distance_from_camera = target_pose_camera.p.norm();
279 double distortion_factor = target_pose_fbs->distortion_factor();
280
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700281 double distance_threshold = 5.0;
282 if (distance_from_camera > distance_threshold) {
283 ignore_count_++;
284 LOG(INFO) << "Ignored " << ignore_count_ << " AprilTags with distance "
285 << distance_from_camera << " > " << distance_threshold;
Maxwell Henderson123c8172024-03-01 22:54:16 -0800286 continue;
287 }
288
289 CHECK(map.has_monotonic_timestamp_ns())
290 << "Need detection timestamps for mapping";
291
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700292 // Detection is usable, so store it
Maxwell Henderson123c8172024-03-01 22:54:16 -0800293 timestamped_target_detections_.emplace_back(
294 DataAdapter::TimestampedDetection{
295 .time = node_distributed_time,
296 .H_robot_target = H_robot_target,
297 .distance_from_camera = distance_from_camera,
298 .distortion_factor = distortion_factor,
299 .id = static_cast<TargetMapper::TargetId>(target_pose.id)});
300
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700301 if (absl::GetFlag(FLAGS_visualize_solver)) {
Maxwell Henderson123c8172024-03-01 22:54:16 -0800302 // If we've already drawn this camera_name in the current image,
303 // display the image before clearing and adding the new poses
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700304 if (drawn_cameras_.count(camera_name) != 0) {
Maxwell Henderson123c8172024-03-01 22:54:16 -0800305 display_count_++;
306 cv::putText(vis_robot_.image_,
307 "Poses #" + std::to_string(display_count_),
308 cv::Point(600, 10), cv::FONT_HERSHEY_PLAIN, 1.0,
309 cv::Scalar(255, 255, 255));
310
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700311 if (display_count_ >= absl::GetFlag(FLAGS_skip_to)) {
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700312 VLOG(1) << "Showing image for camera " << camera_name
Maxwell Henderson123c8172024-03-01 22:54:16 -0800313 << " since we've drawn it already";
314 cv::imshow("View", vis_robot_.image_);
315 // Pause if delta_T is too large, but only after first image (to make
Jim Ostrowski67726282024-03-24 14:39:33 -0700316 // sure the delta's are correct)
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700317 if (max_delta_T_world_robot_ >
318 absl::GetFlag(FLAGS_pause_on_distance) &&
Maxwell Henderson123c8172024-03-01 22:54:16 -0800319 display_count_ > 1) {
320 LOG(INFO) << "Pausing since the delta between robot estimates is "
321 << max_delta_T_world_robot_ << " which is > threshold of "
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700322 << absl::GetFlag(FLAGS_pause_on_distance);
Maxwell Henderson123c8172024-03-01 22:54:16 -0800323 cv::waitKey(0);
324 } else {
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700325 cv::waitKey(absl::GetFlag(FLAGS_wait_key));
Maxwell Henderson123c8172024-03-01 22:54:16 -0800326 }
327 max_delta_T_world_robot_ = 0.0;
328 } else {
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700329 VLOG(2) << "At poses #" << std::to_string(display_count_);
Maxwell Henderson123c8172024-03-01 22:54:16 -0800330 }
331 vis_robot_.ClearImage();
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700332 drawn_cameras_.clear();
Maxwell Henderson123c8172024-03-01 22:54:16 -0800333 }
334
335 Eigen::Affine3d H_world_target = PoseUtils::Pose3dToAffine3d(
336 kFixedTargetMapper.GetTargetPoseById(target_pose_fbs->id())->pose);
337 Eigen::Affine3d H_world_robot = H_world_target * H_robot_target.inverse();
338 VLOG(2) << camera_name << ", id " << target_pose_fbs->id()
339 << ", t = " << node_distributed_time
340 << ", pose_error = " << target_pose_fbs->pose_error()
341 << ", pose_error_ratio = " << target_pose_fbs->pose_error_ratio()
342 << ", robot_pos (x,y,z) = "
343 << H_world_robot.translation().transpose();
344
Jim Ostrowski67726282024-03-24 14:39:33 -0700345 label << "id " << target_pose_fbs->id()
346 << ": err (% of max): " << target_pose_fbs->pose_error() << " ("
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700347 << (target_pose_fbs->pose_error() /
348 absl::GetFlag(FLAGS_max_pose_error))
Jim Ostrowski67726282024-03-24 14:39:33 -0700349 << ") err_ratio: " << target_pose_fbs->pose_error_ratio() << " ";
Maxwell Henderson123c8172024-03-01 22:54:16 -0800350
351 vis_robot_.DrawRobotOutline(H_world_robot, camera_name,
352 kOrinColors.at(camera_name));
353 vis_robot_.DrawFrameAxes(H_world_target,
354 std::to_string(target_pose_fbs->id()),
355 kOrinColors.at(camera_name));
356
357 double delta_T_world_robot =
358 (H_world_robot.translation() - last_H_world_robot_.translation())
359 .norm();
360 max_delta_T_world_robot_ =
361 std::max(delta_T_world_robot, max_delta_T_world_robot_);
362
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700363 VLOG(1) << "Drew in info for camera " << camera_name << " and target #"
Maxwell Henderson123c8172024-03-01 22:54:16 -0800364 << target_pose_fbs->id();
365 drew = true;
366 last_draw_time_ = node_distributed_time;
367 last_H_world_robot_ = H_world_robot;
368 }
369 }
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700370 if (absl::GetFlag(FLAGS_visualize_solver)) {
Maxwell Henderson123c8172024-03-01 22:54:16 -0800371 if (drew) {
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700372 // Collect all the labels from a given camera, and add the text
373 // TODO: Need to fix this one
Jim Ostrowski67726282024-03-24 14:39:33 -0700374 int position_number = camera_ordering_map[camera_name];
Maxwell Henderson123c8172024-03-01 22:54:16 -0800375 cv::putText(vis_robot_.image_, label.str(),
Jim Ostrowski67726282024-03-24 14:39:33 -0700376 cv::Point(10, 30 + 20 * position_number),
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700377 cv::FONT_HERSHEY_PLAIN, 1.0, kOrinColors.at(camera_name));
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700378 drawn_cameras_.emplace(camera_name);
Maxwell Henderson123c8172024-03-01 22:54:16 -0800379 } else if (node_distributed_time - last_draw_time_ >
380 std::chrono::milliseconds(30) &&
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700381 display_count_ >= absl::GetFlag(FLAGS_skip_to) && drew) {
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700382 // TODO: Check on 30ms value-- does this make sense?
383 double delta_t = (node_distributed_time - last_draw_time_).count() / 1e6;
384 VLOG(1) << "Last result was " << delta_t << "ms ago";
385 cv::putText(vis_robot_.image_, "No detections in last 30ms",
386 cv::Point(10, 0), cv::FONT_HERSHEY_PLAIN, 1.0,
387 kOrinColors.at(camera_name));
Maxwell Henderson123c8172024-03-01 22:54:16 -0800388 // Display and clear the image if we haven't draw in a while
389 VLOG(1) << "Displaying image due to time lapse";
390 cv::imshow("View", vis_robot_.image_);
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700391 cv::waitKey(absl::GetFlag(FLAGS_wait_key));
Maxwell Henderson123c8172024-03-01 22:54:16 -0800392 max_delta_T_world_robot_ = 0.0;
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700393 drawn_cameras_.clear();
Maxwell Henderson123c8172024-03-01 22:54:16 -0800394 }
395 }
396}
397
398void TargetMapperReplay::HandleNodeCaptures(
399 aos::EventLoop *mapping_event_loop,
400 frc971::constants::ConstantsFetcher<y2024::Constants> *constants_fetcher,
401 int camera_number) {
402 // Get the camera extrinsics
Jim Ostrowski67726282024-03-24 14:39:33 -0700403 std::string node_name =
404 std::string(mapping_event_loop->node()->name()->string_view());
Maxwell Henderson123c8172024-03-01 22:54:16 -0800405 const auto *calibration = FindCameraCalibration(
Jim Ostrowski67726282024-03-24 14:39:33 -0700406 constants_fetcher->constants(), node_name, camera_number);
Maxwell Henderson123c8172024-03-01 22:54:16 -0800407 cv::Mat extrinsics_cv = frc971::vision::CameraExtrinsics(calibration).value();
408 Eigen::Matrix4d extrinsics_matrix;
409 cv::cv2eigen(extrinsics_cv, extrinsics_matrix);
410 const auto extrinsics = Eigen::Affine3d(extrinsics_matrix);
411 std::string camera_name = absl::StrFormat(
412 "/%s/camera%d", mapping_event_loop->node()->name()->str(), camera_number);
413
414 mapping_event_loop->MakeWatcher(
415 camera_name.c_str(), [this, mapping_event_loop, extrinsics,
416 camera_name](const TargetMap &map) {
417 aos::distributed_clock::time_point node_distributed_time =
418 reader_->event_loop_factory()
419 ->GetNodeEventLoopFactory(mapping_event_loop->node())
420 ->ToDistributedClock(aos::monotonic_clock::time_point(
421 aos::monotonic_clock::duration(
422 map.monotonic_timestamp_ns())));
423
424 HandleAprilTags(map, node_distributed_time, camera_name, extrinsics);
425 });
426}
427
428void TargetMapperReplay::MaybeSolve() {
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700429 if (absl::GetFlag(FLAGS_solve)) {
Maxwell Henderson123c8172024-03-01 22:54:16 -0800430 auto target_constraints =
431 DataAdapter::MatchTargetDetections(timestamped_target_detections_);
432
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700433 if (absl::GetFlag(FLAGS_split_field)) {
Jim Ostrowski5ff3c562024-03-20 20:35:11 -0700434 // Remove constraints between the two sides of the field - these are
435 // basically garbage because of how far the camera is. We will use seeding
436 // below to connect the two sides
437 target_constraints.erase(
438 std::remove_if(
439 target_constraints.begin(), target_constraints.end(),
440 [](const auto &constraint) {
441 return (
442 kIdAllianceMap[static_cast<uint>(constraint.id_begin)] !=
443 kIdAllianceMap[static_cast<uint>(constraint.id_end)]);
444 }),
445 target_constraints.end());
446 }
Maxwell Henderson123c8172024-03-01 22:54:16 -0800447
448 LOG(INFO) << "Solving for locations of tags with "
449 << target_constraints.size() << " constraints";
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700450 TargetMapper mapper(absl::GetFlag(FLAGS_json_path), target_constraints);
451 mapper.Solve(absl::GetFlag(FLAGS_field_name),
452 absl::GetFlag(FLAGS_output_dir));
Maxwell Henderson123c8172024-03-01 22:54:16 -0800453
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700454 if (!absl::GetFlag(FLAGS_dump_constraints_to).empty()) {
455 mapper.DumpConstraints(absl::GetFlag(FLAGS_dump_constraints_to));
Maxwell Henderson123c8172024-03-01 22:54:16 -0800456 }
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700457 if (!absl::GetFlag(FLAGS_dump_stats_to).empty()) {
458 mapper.DumpStats(absl::GetFlag(FLAGS_dump_stats_to));
Maxwell Henderson123c8172024-03-01 22:54:16 -0800459 }
Jim Ostrowskif41b0942024-03-24 18:05:02 -0700460 mapper.PrintDiffs();
Maxwell Henderson123c8172024-03-01 22:54:16 -0800461 }
462}
463
464void MappingMain(int argc, char *argv[]) {
465 std::vector<DataAdapter::TimestampedDetection> timestamped_target_detections;
466
467 std::optional<aos::FlatbufferDetachedBuffer<aos::Configuration>> config =
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700468 (absl::GetFlag(FLAGS_config).empty()
Maxwell Henderson123c8172024-03-01 22:54:16 -0800469 ? std::nullopt
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700470 : std::make_optional(
471 aos::configuration::ReadConfig(absl::GetFlag(FLAGS_config))));
Maxwell Henderson123c8172024-03-01 22:54:16 -0800472
473 // Open logfiles
474 aos::logger::LogReader reader(
475 aos::logger::SortParts(aos::logger::FindLogs(argc, argv)),
476 config.has_value() ? &config->message() : nullptr);
477
478 TargetMapperReplay mapper_replay(&reader);
479 reader.event_loop_factory()->Run();
480 mapper_replay.MaybeSolve();
481}
482
483} // namespace y2024::vision
484
485int main(int argc, char **argv) {
486 aos::InitGoogle(&argc, &argv);
487 y2024::vision::MappingMain(argc, argv);
488}