blob: f33a83ae90b124ce8509bc3a05db5e6689ede384 [file] [log] [blame]
Philipp Schrader790cb542023-07-05 21:06:52 -07001#include "Eigen/Dense"
2#include "opencv2/aruco.hpp"
3#include "opencv2/calib3d.hpp"
4#include "opencv2/core/eigen.hpp"
5#include "opencv2/features2d.hpp"
6#include "opencv2/highgui.hpp"
7#include "opencv2/highgui/highgui.hpp"
8#include "opencv2/imgproc.hpp"
9
Jim Ostrowskiaec5dd22023-02-27 22:17:53 -080010#include "aos/configuration.h"
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080011#include "aos/events/logging/log_reader.h"
12#include "aos/events/simulated_event_loop.h"
13#include "aos/init.h"
Jim Ostrowski68965cd2023-03-01 20:32:51 -080014#include "aos/util/mcap_logger.h"
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080015#include "frc971/control_loops/pose.h"
milind-u16e3a082023-01-21 13:53:43 -080016#include "frc971/vision/calibration_generated.h"
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080017#include "frc971/vision/target_mapper.h"
Jim Ostrowski49be8232023-03-23 01:00:14 -070018#include "frc971/vision/visualize_robot.h"
milind-uc5a494f2023-02-24 15:39:22 -080019#include "y2023/constants/simulated_constants_sender.h"
milind-u09fb1252023-01-28 19:21:41 -080020#include "y2023/vision/aprilrobotics.h"
James Kuszmauld67f6d22023-02-05 17:37:25 -080021#include "y2023/vision/vision_util.h"
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080022
Austin Schuh99f7c6a2024-06-25 22:07:44 -070023ABSL_FLAG(std::string, config, "",
24 "If set, override the log's config file with this one.");
25ABSL_FLAG(std::string, constants_path, "y2023/constants/constants.json",
26 "Path to the constant file");
27ABSL_FLAG(std::string, dump_constraints_to, "/tmp/mapping_constraints.txt",
28 "Write the target constraints to this path");
29ABSL_FLAG(std::string, dump_stats_to, "/tmp/mapping_stats.txt",
30 "Write the mapping stats to this path");
31ABSL_FLAG(std::string, field_name, "charged_up",
32 "Field name, for the output json filename and flatbuffer field");
33ABSL_FLAG(std::string, json_path, "y2023/vision/maps/target_map.json",
34 "Specify path for json with initial pose guesses.");
35ABSL_FLAG(double, max_pose_error, 1e-6,
36 "Throw out target poses with a higher pose error than this");
37ABSL_FLAG(double, max_pose_error_ratio, 0.4,
38 "Throw out target poses with a higher pose error ratio than this");
39ABSL_FLAG(std::string, mcap_output_path, "", "Log to output.");
40ABSL_FLAG(std::string, output_dir, "y2023/vision/maps",
41 "Directory to write solved target map to");
42ABSL_FLAG(double, pause_on_distance, 1.0,
43 "Pause if two consecutive implied robot positions differ by more "
44 "than this many meters");
45ABSL_FLAG(std::string, pi, "pi1",
46 "Pi name to generate mcap log for; defaults to pi1.");
47ABSL_FLAG(uint64_t, skip_to, 1,
48 "Start at combined image of this number (1 is the first image)");
49ABSL_FLAG(bool, solve, true, "Whether to solve for the field's target map.");
50ABSL_FLAG(int32_t, team_number, 0,
51 "Required: Use the calibration for a node with this team number");
52ABSL_FLAG(uint64_t, wait_key, 1,
53 "Time in ms to wait between images, if no click (0 to wait "
54 "indefinitely until click).");
Jim Ostrowski2f2685f2023-03-25 11:57:54 -070055
Austin Schuh99f7c6a2024-06-25 22:07:44 -070056ABSL_DECLARE_FLAG(int32_t, frozen_target_id);
57ABSL_DECLARE_FLAG(int32_t, min_target_id);
58ABSL_DECLARE_FLAG(int32_t, max_target_id);
59ABSL_DECLARE_FLAG(bool, visualize_solver);
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -080060
Stephan Pleinesf63bde82024-01-13 15:59:33 -080061namespace y2023::vision {
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080062using frc971::vision::DataAdapter;
milind-u16e3a082023-01-21 13:53:43 -080063using frc971::vision::ImageCallback;
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080064using frc971::vision::PoseUtils;
milind-u09fb1252023-01-28 19:21:41 -080065using frc971::vision::TargetMap;
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080066using frc971::vision::TargetMapper;
milind-ua30a4a12023-03-24 20:49:41 -070067using frc971::vision::VisualizeRobot;
milind-u16e3a082023-01-21 13:53:43 -080068namespace calibration = frc971::vision::calibration;
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080069
milind-u2ab4db12023-03-25 21:59:23 -070070// Class to handle reading target poses from a replayed log,
71// displaying various debug info, and passing the poses to
72// frc971::vision::TargetMapper for field mapping.
73class TargetMapperReplay {
74 public:
75 TargetMapperReplay(aos::logger::LogReader *reader);
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080076
milind-u2ab4db12023-03-25 21:59:23 -070077 // Solves for the target poses with the accumulated detections if FLAGS_solve.
78 void MaybeSolve();
79
80 private:
81 static constexpr int kImageWidth = 1280;
82 // Map from pi node name to color for drawing
83 static const std::map<std::string, cv::Scalar> kPiColors;
84 // Contains fixed target poses without solving, for use with visualization
85 static const TargetMapper kFixedTargetMapper;
86
87 // Change reference frame from camera to robot
88 static Eigen::Affine3d CameraToRobotDetection(Eigen::Affine3d H_camera_target,
89 Eigen::Affine3d extrinsics);
90
91 // Adds april tag detections into the detection list, and handles
92 // visualization
93 void HandleAprilTags(const TargetMap &map,
94 aos::distributed_clock::time_point pi_distributed_time,
95 std::string node_name, Eigen::Affine3d extrinsics);
96
97 // Gets images from the given pi and passes apriltag positions to
98 // HandleAprilTags()
milind-u8b0f4782023-04-15 13:59:29 -070099 void HandlePiCaptures(aos::EventLoop *mapping_event_loop);
milind-u2ab4db12023-03-25 21:59:23 -0700100
101 aos::logger::LogReader *reader_;
102 // April tag detections from all pis
103 std::vector<DataAdapter::TimestampedDetection> timestamped_target_detections_;
milind-u2ab4db12023-03-25 21:59:23 -0700104
105 VisualizeRobot vis_robot_;
106 // Set of node names which are currently drawn on the display
107 std::set<std::string> drawn_nodes_;
108 // Number of frames displayed
109 size_t display_count_;
110 // Last time we drew onto the display image.
111 // This is different from when we actually call imshow() to update
112 // the display window
113 aos::distributed_clock::time_point last_draw_time_;
114
milind-u8cc03da2023-03-25 23:00:39 -0700115 Eigen::Affine3d last_H_world_robot_;
116 // Maximum distance between consecutive T_world_robot's in one display frame,
117 // used to determine if we need to pause for the user to see this frame
118 // clearly
119 double max_delta_T_world_robot_;
120
milind-u2ab4db12023-03-25 21:59:23 -0700121 std::vector<std::unique_ptr<aos::EventLoop>> mapping_event_loops_;
122
123 std::unique_ptr<aos::EventLoop> mcap_event_loop_;
124 std::unique_ptr<aos::McapLogger> relogger_;
125};
126
127const auto TargetMapperReplay::kPiColors = std::map<std::string, cv::Scalar>{
milind-ua30a4a12023-03-24 20:49:41 -0700128 {"pi1", cv::Scalar(255, 0, 255)},
129 {"pi2", cv::Scalar(255, 255, 0)},
130 {"pi3", cv::Scalar(0, 255, 255)},
131 {"pi4", cv::Scalar(255, 165, 0)},
132};
Jim Ostrowski49be8232023-03-23 01:00:14 -0700133
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700134const auto TargetMapperReplay::kFixedTargetMapper = TargetMapper(
135 absl::GetFlag(FLAGS_json_path), ceres::examples::VectorOfConstraints{});
milind-u2ab4db12023-03-25 21:59:23 -0700136
137Eigen::Affine3d TargetMapperReplay::CameraToRobotDetection(
138 Eigen::Affine3d H_camera_target, Eigen::Affine3d extrinsics) {
139 const Eigen::Affine3d H_robot_camera = extrinsics;
140 const Eigen::Affine3d H_robot_target = H_robot_camera * H_camera_target;
141 return H_robot_target;
142}
143
144TargetMapperReplay::TargetMapperReplay(aos::logger::LogReader *reader)
145 : reader_(reader),
146 timestamped_target_detections_(),
milind-u2ab4db12023-03-25 21:59:23 -0700147 vis_robot_(cv::Size(1280, 1000)),
148 drawn_nodes_(),
149 display_count_(0),
milind-u8cc03da2023-03-25 23:00:39 -0700150 last_draw_time_(aos::distributed_clock::min_time),
151 last_H_world_robot_(Eigen::Matrix4d::Identity()),
152 max_delta_T_world_robot_(0.0) {
milind-u2ab4db12023-03-25 21:59:23 -0700153 constexpr size_t kNumPis = 4;
milind-u8b0f4782023-04-15 13:59:29 -0700154 // TODO(milind): add a flag to support replaying april detection from full
155 // logs as well.
milind-u2ab4db12023-03-25 21:59:23 -0700156 for (size_t i = 1; i <= kNumPis; i++) {
milind-u2ab4db12023-03-25 21:59:23 -0700157 reader_->RemapLoggedChannel(absl::StrFormat("/pi%u/constants", i),
158 "y2023.Constants");
159 }
160
161 reader_->RemapLoggedChannel("/imu/constants", "y2023.Constants");
Jim Ostrowski68c321d2023-11-14 21:36:28 -0800162 reader_->RemapLoggedChannel("/logger/constants", "y2023.Constants");
163 reader_->RemapLoggedChannel("/roborio/constants", "y2023.Constants");
milind-u2ab4db12023-03-25 21:59:23 -0700164
165 reader_->Register();
166
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700167 SendSimulationConstants(reader_->event_loop_factory(),
168 absl::GetFlag(FLAGS_team_number),
169 absl::GetFlag(FLAGS_constants_path));
milind-u2ab4db12023-03-25 21:59:23 -0700170
171 for (size_t i = 1; i < kNumPis; i++) {
172 std::string node_name = "pi" + std::to_string(i);
173 const aos::Node *pi =
174 aos::configuration::GetNode(reader_->configuration(), node_name);
milind-u2ab4db12023-03-25 21:59:23 -0700175 mapping_event_loops_.emplace_back(
176 reader_->event_loop_factory()->MakeEventLoop(node_name + "_mapping",
177 pi));
178 HandlePiCaptures(
milind-u2ab4db12023-03-25 21:59:23 -0700179 mapping_event_loops_[mapping_event_loops_.size() - 1].get());
180 }
181
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700182 if (!absl::GetFlag(FLAGS_mcap_output_path).empty()) {
183 LOG(INFO) << "Writing out mcap file to "
184 << absl::GetFlag(FLAGS_mcap_output_path);
185 const aos::Node *node = aos::configuration::GetNode(
186 reader_->configuration(), absl::GetFlag(FLAGS_pi));
milind-u2ab4db12023-03-25 21:59:23 -0700187 reader_->event_loop_factory()->GetNodeEventLoopFactory(node)->OnStartup(
188 [this, node]() {
189 mcap_event_loop_ =
190 reader_->event_loop_factory()->MakeEventLoop("mcap", node);
191 relogger_ = std::make_unique<aos::McapLogger>(
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700192 mcap_event_loop_.get(), absl::GetFlag(FLAGS_mcap_output_path),
milind-u2ab4db12023-03-25 21:59:23 -0700193 aos::McapLogger::Serialization::kFlatbuffer,
194 aos::McapLogger::CanonicalChannelNames::kShortened,
195 aos::McapLogger::Compression::kLz4);
196 });
197 }
198
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700199 if (absl::GetFlag(FLAGS_visualize_solver)) {
milind-u2ab4db12023-03-25 21:59:23 -0700200 vis_robot_.ClearImage();
201 const double kFocalLength = 500.0;
202 vis_robot_.SetDefaultViewpoint(kImageWidth, kFocalLength);
203 }
204}
205
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800206// Add detected apriltag poses relative to the robot to
207// timestamped_target_detections
milind-u2ab4db12023-03-25 21:59:23 -0700208void TargetMapperReplay::HandleAprilTags(
209 const TargetMap &map,
210 aos::distributed_clock::time_point pi_distributed_time,
211 std::string node_name, Eigen::Affine3d extrinsics) {
milind-ua30a4a12023-03-24 20:49:41 -0700212 bool drew = false;
213 std::stringstream label;
214 label << node_name << " - ";
215
milind-u3f5f83c2023-01-29 15:23:51 -0800216 for (const auto *target_pose_fbs : *map.target_poses()) {
milind-ufbc5c812023-04-06 21:24:29 -0700217 // Skip detections with invalid ids
milind-u8f4e43e2023-04-09 17:11:19 -0700218 if (static_cast<TargetMapper::TargetId>(target_pose_fbs->id()) <
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700219 absl::GetFlag(FLAGS_min_target_id) ||
milind-u8f4e43e2023-04-09 17:11:19 -0700220 static_cast<TargetMapper::TargetId>(target_pose_fbs->id()) >
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700221 absl::GetFlag(FLAGS_max_target_id)) {
milind-u8f4e43e2023-04-09 17:11:19 -0700222 VLOG(1) << "Skipping tag with invalid id of " << target_pose_fbs->id();
milind-ufbc5c812023-04-06 21:24:29 -0700223 continue;
224 }
225
milind-u5ddd5152023-03-04 15:19:17 -0800226 // Skip detections with high pose errors
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700227 if (target_pose_fbs->pose_error() > absl::GetFlag(FLAGS_max_pose_error)) {
milind-u8f4e43e2023-04-09 17:11:19 -0700228 VLOG(1) << "Skipping tag " << target_pose_fbs->id()
milind-ude9045f2023-03-25 18:17:12 -0700229 << " due to pose error of " << target_pose_fbs->pose_error();
230 continue;
231 }
232 // Skip detections with high pose error ratios
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700233 if (target_pose_fbs->pose_error_ratio() >
234 absl::GetFlag(FLAGS_max_pose_error_ratio)) {
milind-u8f4e43e2023-04-09 17:11:19 -0700235 VLOG(1) << "Skipping tag " << target_pose_fbs->id()
milind-ude9045f2023-03-25 18:17:12 -0700236 << " due to pose error ratio of "
237 << target_pose_fbs->pose_error_ratio();
milind-u5ddd5152023-03-04 15:19:17 -0800238 continue;
239 }
240
milind-u3f5f83c2023-01-29 15:23:51 -0800241 const TargetMapper::TargetPose target_pose =
242 PoseUtils::TargetPoseFromFbs(*target_pose_fbs);
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800243
milind-uee67abd2023-02-23 18:26:55 -0800244 Eigen::Affine3d H_camera_target =
milind-u3f5f83c2023-01-29 15:23:51 -0800245 Eigen::Translation3d(target_pose.pose.p) * target_pose.pose.q;
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800246 Eigen::Affine3d H_robot_target =
milind-uee67abd2023-02-23 18:26:55 -0800247 CameraToRobotDetection(H_camera_target, extrinsics);
Milind Upadhyayebf93ee2023-01-05 14:12:58 -0800248
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800249 ceres::examples::Pose3d target_pose_camera =
milind-uee67abd2023-02-23 18:26:55 -0800250 PoseUtils::Affine3dToPose3d(H_camera_target);
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800251 double distance_from_camera = target_pose_camera.p.norm();
milind-ud62f80a2023-03-04 16:37:09 -0800252 double distortion_factor = target_pose_fbs->distortion_factor();
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800253
milind-u09fb1252023-01-28 19:21:41 -0800254 CHECK(map.has_monotonic_timestamp_ns())
255 << "Need detection timestamps for mapping";
256
milind-u2ab4db12023-03-25 21:59:23 -0700257 timestamped_target_detections_.emplace_back(
Milind Upadhyayebf93ee2023-01-05 14:12:58 -0800258 DataAdapter::TimestampedDetection{
259 .time = pi_distributed_time,
260 .H_robot_target = H_robot_target,
261 .distance_from_camera = distance_from_camera,
milind-ud62f80a2023-03-04 16:37:09 -0800262 .distortion_factor = distortion_factor,
milind-u3f5f83c2023-01-29 15:23:51 -0800263 .id = static_cast<TargetMapper::TargetId>(target_pose.id)});
Jim Ostrowski49be8232023-03-23 01:00:14 -0700264
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700265 if (absl::GetFlag(FLAGS_visualize_solver)) {
Jim Ostrowski7fde9b02023-09-09 23:33:58 -0700266 // If we've already drawn this node_name in the current image,
267 // display the image before clearing and adding the new poses
milind-u2ab4db12023-03-25 21:59:23 -0700268 if (drawn_nodes_.count(node_name) != 0) {
269 display_count_++;
270 cv::putText(vis_robot_.image_,
271 "Poses #" + std::to_string(display_count_),
milind-ua30a4a12023-03-24 20:49:41 -0700272 cv::Point(600, 10), cv::FONT_HERSHEY_PLAIN, 1.0,
273 cv::Scalar(255, 255, 255));
274
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700275 if (display_count_ >= absl::GetFlag(FLAGS_skip_to)) {
Jim Ostrowski7fde9b02023-09-09 23:33:58 -0700276 VLOG(1) << "Showing image for node " << node_name
277 << " since we've drawn it already";
milind-u2ab4db12023-03-25 21:59:23 -0700278 cv::imshow("View", vis_robot_.image_);
Jim Ostrowski7fde9b02023-09-09 23:33:58 -0700279 // Pause if delta_T is too large, but only after first image (to make
280 // sure the delta's are correct
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700281 if (max_delta_T_world_robot_ >
282 absl::GetFlag(FLAGS_pause_on_distance) &&
Jim Ostrowski7fde9b02023-09-09 23:33:58 -0700283 display_count_ > 1) {
284 LOG(INFO) << "Pausing since the delta between robot estimates is "
285 << max_delta_T_world_robot_ << " which is > threshold of "
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700286 << absl::GetFlag(FLAGS_pause_on_distance);
Jim Ostrowski7fde9b02023-09-09 23:33:58 -0700287 cv::waitKey(0);
288 } else {
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700289 cv::waitKey(absl::GetFlag(FLAGS_wait_key));
Jim Ostrowski7fde9b02023-09-09 23:33:58 -0700290 }
milind-u8cc03da2023-03-25 23:00:39 -0700291 max_delta_T_world_robot_ = 0.0;
milind-ude9045f2023-03-25 18:17:12 -0700292 } else {
milind-u2ab4db12023-03-25 21:59:23 -0700293 VLOG(1) << "At poses #" << std::to_string(display_count_);
milind-ude9045f2023-03-25 18:17:12 -0700294 }
milind-u2ab4db12023-03-25 21:59:23 -0700295 vis_robot_.ClearImage();
296 drawn_nodes_.clear();
milind-ua30a4a12023-03-24 20:49:41 -0700297 }
298
Jim Ostrowski49be8232023-03-23 01:00:14 -0700299 Eigen::Affine3d H_world_target = PoseUtils::Pose3dToAffine3d(
milind-u2ab4db12023-03-25 21:59:23 -0700300 kFixedTargetMapper.GetTargetPoseById(target_pose_fbs->id())->pose);
Jim Ostrowski49be8232023-03-23 01:00:14 -0700301 Eigen::Affine3d H_world_robot = H_world_target * H_robot_target.inverse();
Jim Ostrowski7fde9b02023-09-09 23:33:58 -0700302 VLOG(2) << node_name << ", id " << target_pose_fbs->id()
milind-ude9045f2023-03-25 18:17:12 -0700303 << ", t = " << pi_distributed_time
304 << ", pose_error = " << target_pose_fbs->pose_error()
305 << ", pose_error_ratio = " << target_pose_fbs->pose_error_ratio()
Jim Ostrowski7fde9b02023-09-09 23:33:58 -0700306 << ", robot_pos (x,y,z) = "
milind-ude9045f2023-03-25 18:17:12 -0700307 << H_world_robot.translation().transpose();
milind-ua30a4a12023-03-24 20:49:41 -0700308
Jim Ostrowski7fde9b02023-09-09 23:33:58 -0700309 label << "id " << target_pose_fbs->id() << ": err (% of max): "
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700310 << (target_pose_fbs->pose_error() /
311 absl::GetFlag(FLAGS_max_pose_error))
Jim Ostrowski7fde9b02023-09-09 23:33:58 -0700312 << " err_ratio: " << target_pose_fbs->pose_error_ratio() << " ";
milind-ua30a4a12023-03-24 20:49:41 -0700313
Jim Ostrowski7fde9b02023-09-09 23:33:58 -0700314 vis_robot_.DrawRobotOutline(H_world_robot, node_name,
milind-ua30a4a12023-03-24 20:49:41 -0700315 kPiColors.at(node_name));
milind-u2ab4db12023-03-25 21:59:23 -0700316 vis_robot_.DrawFrameAxes(H_world_target,
milind-ua30a4a12023-03-24 20:49:41 -0700317 std::to_string(target_pose_fbs->id()),
318 kPiColors.at(node_name));
milind-u8cc03da2023-03-25 23:00:39 -0700319
320 double delta_T_world_robot =
321 (H_world_robot.translation() - last_H_world_robot_.translation())
322 .norm();
323 max_delta_T_world_robot_ =
324 std::max(delta_T_world_robot, max_delta_T_world_robot_);
325
Jim Ostrowski7fde9b02023-09-09 23:33:58 -0700326 VLOG(1) << "Drew in info for robot " << node_name << " and target #"
327 << target_pose_fbs->id();
milind-ua30a4a12023-03-24 20:49:41 -0700328 drew = true;
milind-u2ab4db12023-03-25 21:59:23 -0700329 last_draw_time_ = pi_distributed_time;
milind-u8cc03da2023-03-25 23:00:39 -0700330 last_H_world_robot_ = H_world_robot;
Jim Ostrowski49be8232023-03-23 01:00:14 -0700331 }
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800332 }
milind-ua30a4a12023-03-24 20:49:41 -0700333
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700334 if (absl::GetFlag(FLAGS_visualize_solver)) {
Jim Ostrowski7fde9b02023-09-09 23:33:58 -0700335 if (drew) {
336 // Collect all the labels from a given node, and add the text
337 size_t pi_number =
338 static_cast<size_t>(node_name[node_name.size() - 1] - '0');
339 cv::putText(vis_robot_.image_, label.str(),
340 cv::Point(10, 10 + 20 * pi_number), cv::FONT_HERSHEY_PLAIN,
341 1.0, kPiColors.at(node_name));
342
343 drawn_nodes_.emplace(node_name);
344 } else if (pi_distributed_time - last_draw_time_ >
345 std::chrono::milliseconds(30) &&
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700346 display_count_ >= absl::GetFlag(FLAGS_skip_to)) {
Jim Ostrowski7fde9b02023-09-09 23:33:58 -0700347 cv::putText(vis_robot_.image_, "No detections", cv::Point(10, 0),
348 cv::FONT_HERSHEY_PLAIN, 1.0, kPiColors.at(node_name));
349 // Display and clear the image if we haven't draw in a while
350 VLOG(1) << "Displaying image due to time lapse";
351 cv::imshow("View", vis_robot_.image_);
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700352 cv::waitKey(absl::GetFlag(FLAGS_wait_key));
Jim Ostrowski7fde9b02023-09-09 23:33:58 -0700353 vis_robot_.ClearImage();
354 max_delta_T_world_robot_ = 0.0;
355 drawn_nodes_.clear();
356 }
milind-ua30a4a12023-03-24 20:49:41 -0700357 }
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800358}
359
milind-u8b0f4782023-04-15 13:59:29 -0700360void TargetMapperReplay::HandlePiCaptures(aos::EventLoop *mapping_event_loop) {
milind-uf2a4e322023-02-01 19:33:10 -0800361 // Get the camera extrinsics
milind-u8b0f4782023-04-15 13:59:29 -0700362 const frc971::constants::ConstantsFetcher<Constants> constants(
363 mapping_event_loop);
364 const auto *calibration = FindCameraCalibration(
365 constants.constants(), mapping_event_loop->node()->name()->string_view());
366 cv::Mat extrinsics_cv = CameraExtrinsics(calibration).value();
milind-uf2a4e322023-02-01 19:33:10 -0800367 Eigen::Matrix4d extrinsics_matrix;
368 cv::cv2eigen(extrinsics_cv, extrinsics_matrix);
369 const auto extrinsics = Eigen::Affine3d(extrinsics_matrix);
370
Austin Schuh612d95d2023-10-21 00:01:40 -0700371 mapping_event_loop->MakeWatcher(
372 "/camera", [this, mapping_event_loop, extrinsics](const TargetMap &map) {
373 aos::distributed_clock::time_point pi_distributed_time =
374 reader_->event_loop_factory()
375 ->GetNodeEventLoopFactory(mapping_event_loop->node())
376 ->ToDistributedClock(aos::monotonic_clock::time_point(
377 aos::monotonic_clock::duration(
378 map.monotonic_timestamp_ns())));
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800379
Austin Schuh612d95d2023-10-21 00:01:40 -0700380 std::string node_name = mapping_event_loop->node()->name()->str();
381 HandleAprilTags(map, pi_distributed_time, node_name, extrinsics);
382 });
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800383}
384
milind-u2ab4db12023-03-25 21:59:23 -0700385void TargetMapperReplay::MaybeSolve() {
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700386 if (absl::GetFlag(FLAGS_solve)) {
milind-u2ab4db12023-03-25 21:59:23 -0700387 auto target_constraints =
388 DataAdapter::MatchTargetDetections(timestamped_target_detections_);
389
milind-ufbc5c812023-04-06 21:24:29 -0700390 // Remove constraints between the two sides of the field - these are
391 // basically garbage because of how far the camera is. We will use seeding
392 // below to connect the two sides
393 target_constraints.erase(
394 std::remove_if(target_constraints.begin(), target_constraints.end(),
395 [](const auto &constraint) {
396 constexpr TargetMapper::TargetId kMaxRedId = 4;
397 TargetMapper::TargetId min_id =
398 std::min(constraint.id_begin, constraint.id_end);
399 TargetMapper::TargetId max_id =
400 std::max(constraint.id_begin, constraint.id_end);
401 return (min_id <= kMaxRedId && max_id > kMaxRedId);
402 }),
403 target_constraints.end());
404
Jim Ostrowski7fde9b02023-09-09 23:33:58 -0700405 LOG(INFO) << "Solving for locations of tags with "
406 << target_constraints.size() << " constraints";
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700407 TargetMapper mapper(absl::GetFlag(FLAGS_json_path), target_constraints);
408 mapper.Solve(absl::GetFlag(FLAGS_field_name),
409 absl::GetFlag(FLAGS_output_dir));
milind-u401de982023-04-14 17:32:03 -0700410
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700411 if (!absl::GetFlag(FLAGS_dump_constraints_to).empty()) {
412 mapper.DumpConstraints(absl::GetFlag(FLAGS_dump_constraints_to));
milind-u401de982023-04-14 17:32:03 -0700413 }
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700414 if (!absl::GetFlag(FLAGS_dump_stats_to).empty()) {
415 mapper.DumpStats(absl::GetFlag(FLAGS_dump_stats_to));
milind-u401de982023-04-14 17:32:03 -0700416 }
milind-u2ab4db12023-03-25 21:59:23 -0700417 }
418}
419
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800420void MappingMain(int argc, char *argv[]) {
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800421 std::vector<DataAdapter::TimestampedDetection> timestamped_target_detections;
422
milind-u4a5ef8a2023-03-05 14:10:23 -0800423 std::optional<aos::FlatbufferDetachedBuffer<aos::Configuration>> config =
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700424 (absl::GetFlag(FLAGS_config).empty()
milind-u4a5ef8a2023-03-05 14:10:23 -0800425 ? std::nullopt
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700426 : std::make_optional(
427 aos::configuration::ReadConfig(absl::GetFlag(FLAGS_config))));
Jim Ostrowskiaec5dd22023-02-27 22:17:53 -0800428
milind-u2ab4db12023-03-25 21:59:23 -0700429 // Open logfiles
milind-u4a5ef8a2023-03-05 14:10:23 -0800430 aos::logger::LogReader reader(
Austin Schuhc1609732023-06-26 11:51:28 -0700431 aos::logger::SortParts(aos::logger::FindLogs(argc, argv)),
milind-u4a5ef8a2023-03-05 14:10:23 -0800432 config.has_value() ? &config->message() : nullptr);
milind-uf3ab8ba2023-02-04 17:56:16 -0800433
milind-u2ab4db12023-03-25 21:59:23 -0700434 TargetMapperReplay mapper_replay(&reader);
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800435 reader.event_loop_factory()->Run();
milind-u2ab4db12023-03-25 21:59:23 -0700436 mapper_replay.MaybeSolve();
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800437}
438
Stephan Pleinesf63bde82024-01-13 15:59:33 -0800439} // namespace y2023::vision
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800440
441int main(int argc, char **argv) {
442 aos::InitGoogle(&argc, &argv);
milind-u16e3a082023-01-21 13:53:43 -0800443 y2023::vision::MappingMain(argc, argv);
Milind Upadhyay915d6002022-12-26 20:37:43 -0800444}