blob: daba90c7868bdb58bdaf187dc4d89e71f497457f [file] [log] [blame]
Jim Ostrowskiaec5dd22023-02-27 22:17:53 -08001#include "aos/configuration.h"
Yash Chainanid5c7f0d2022-11-19 17:05:57 -08002#include "aos/events/logging/log_reader.h"
3#include "aos/events/simulated_event_loop.h"
4#include "aos/init.h"
Jim Ostrowski68965cd2023-03-01 20:32:51 -08005#include "aos/util/mcap_logger.h"
Yash Chainanid5c7f0d2022-11-19 17:05:57 -08006#include "frc971/control_loops/pose.h"
milind-u16e3a082023-01-21 13:53:43 -08007#include "frc971/vision/calibration_generated.h"
Yash Chainanid5c7f0d2022-11-19 17:05:57 -08008#include "frc971/vision/target_mapper.h"
Jim Ostrowski49be8232023-03-23 01:00:14 -07009#include "frc971/vision/visualize_robot.h"
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080010#include "opencv2/aruco.hpp"
11#include "opencv2/calib3d.hpp"
12#include "opencv2/core/eigen.hpp"
13#include "opencv2/features2d.hpp"
14#include "opencv2/highgui.hpp"
15#include "opencv2/highgui/highgui.hpp"
16#include "opencv2/imgproc.hpp"
milind-uc5a494f2023-02-24 15:39:22 -080017#include "y2023/constants/simulated_constants_sender.h"
milind-u09fb1252023-01-28 19:21:41 -080018#include "y2023/vision/aprilrobotics.h"
James Kuszmauld67f6d22023-02-05 17:37:25 -080019#include "y2023/vision/vision_util.h"
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080020
milind-uc5a494f2023-02-24 15:39:22 -080021DEFINE_string(json_path, "y2023/vision/maps/target_map.json",
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080022 "Specify path for json with initial pose guesses.");
milind-u4a5ef8a2023-03-05 14:10:23 -080023DEFINE_string(config, "",
24 "If set, override the log's config file with this one.");
milind-uc5a494f2023-02-24 15:39:22 -080025DEFINE_string(constants_path, "y2023/constants/constants.json",
26 "Path to the constant file");
27DEFINE_string(output_dir, "y2023/vision/maps",
28 "Directory to write solved target map to");
29DEFINE_string(field_name, "charged_up",
30 "Field name, for the output json filename and flatbuffer field");
Jim Ostrowski49be8232023-03-23 01:00:14 -070031DEFINE_int32(team_number, 0,
32 "Required: Use the calibration for a node with this team number");
Jim Ostrowski68965cd2023-03-01 20:32:51 -080033DEFINE_string(mcap_output_path, "/tmp/log.mcap", "Log to output.");
34DEFINE_string(pi, "pi1", "Pi name to generate mcap log for; defaults to pi1.");
milind-u5ddd5152023-03-04 15:19:17 -080035DEFINE_double(max_pose_error, 1e-6,
36 "Throw out target poses with a higher pose error than this");
milind-ude9045f2023-03-25 18:17:12 -070037DEFINE_double(
38 max_pose_error_ratio, 0.4,
39 "Throw out target poses with a higher pose error ratio than this");
milind-ua30a4a12023-03-24 20:49:41 -070040DEFINE_uint64(wait_key, 0,
41 "Time in ms to wait between images, if no click (0 to wait "
42 "indefinitely until click).");
milind-u8cc03da2023-03-25 23:00:39 -070043DEFINE_double(pause_on_distance, 1.0,
44 "Pause if two consecutive implied robot positions differ by more "
45 "than this many meters");
milind-ude9045f2023-03-25 18:17:12 -070046DEFINE_uint64(skip_to, 1,
47 "Start at combined image of this number (1 is the first image)");
milind-ua30a4a12023-03-24 20:49:41 -070048DEFINE_bool(solve, true, "Whether to solve for the field's target map.");
milind-ufbc5c812023-04-06 21:24:29 -070049DEFINE_string(dump_constraints_to, "/tmp/constraints.txt",
50 "Write the target constraints to this path");
milind-u8f4e43e2023-04-09 17:11:19 -070051DECLARE_int32(frozen_target_id);
52DECLARE_int32(min_target_id);
53DECLARE_int32(max_target_id);
54DECLARE_bool(visualize_solver);
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -080055
milind-u16e3a082023-01-21 13:53:43 -080056namespace y2023 {
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080057namespace vision {
58using frc971::vision::DataAdapter;
milind-u16e3a082023-01-21 13:53:43 -080059using frc971::vision::ImageCallback;
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080060using frc971::vision::PoseUtils;
milind-u09fb1252023-01-28 19:21:41 -080061using frc971::vision::TargetMap;
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080062using frc971::vision::TargetMapper;
milind-ua30a4a12023-03-24 20:49:41 -070063using frc971::vision::VisualizeRobot;
milind-u16e3a082023-01-21 13:53:43 -080064namespace calibration = frc971::vision::calibration;
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080065
milind-u2ab4db12023-03-25 21:59:23 -070066// Class to handle reading target poses from a replayed log,
67// displaying various debug info, and passing the poses to
68// frc971::vision::TargetMapper for field mapping.
69class TargetMapperReplay {
70 public:
71 TargetMapperReplay(aos::logger::LogReader *reader);
72 ~TargetMapperReplay();
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080073
milind-u2ab4db12023-03-25 21:59:23 -070074 // Solves for the target poses with the accumulated detections if FLAGS_solve.
75 void MaybeSolve();
76
77 private:
78 static constexpr int kImageWidth = 1280;
79 // Map from pi node name to color for drawing
80 static const std::map<std::string, cv::Scalar> kPiColors;
81 // Contains fixed target poses without solving, for use with visualization
82 static const TargetMapper kFixedTargetMapper;
83
84 // Change reference frame from camera to robot
85 static Eigen::Affine3d CameraToRobotDetection(Eigen::Affine3d H_camera_target,
86 Eigen::Affine3d extrinsics);
87
88 // Adds april tag detections into the detection list, and handles
89 // visualization
90 void HandleAprilTags(const TargetMap &map,
91 aos::distributed_clock::time_point pi_distributed_time,
92 std::string node_name, Eigen::Affine3d extrinsics);
93
94 // Gets images from the given pi and passes apriltag positions to
95 // HandleAprilTags()
96 void HandlePiCaptures(aos::EventLoop *detection_event_loop,
97 aos::EventLoop *mapping_event_loop);
98
99 aos::logger::LogReader *reader_;
100 // April tag detections from all pis
101 std::vector<DataAdapter::TimestampedDetection> timestamped_target_detections_;
102 std::vector<std::unique_ptr<AprilRoboticsDetector>> detectors_;
103
104 VisualizeRobot vis_robot_;
105 // Set of node names which are currently drawn on the display
106 std::set<std::string> drawn_nodes_;
107 // Number of frames displayed
108 size_t display_count_;
109 // Last time we drew onto the display image.
110 // This is different from when we actually call imshow() to update
111 // the display window
112 aos::distributed_clock::time_point last_draw_time_;
113
milind-u8cc03da2023-03-25 23:00:39 -0700114 Eigen::Affine3d last_H_world_robot_;
115 // Maximum distance between consecutive T_world_robot's in one display frame,
116 // used to determine if we need to pause for the user to see this frame
117 // clearly
118 double max_delta_T_world_robot_;
119
milind-u2ab4db12023-03-25 21:59:23 -0700120 std::vector<std::unique_ptr<aos::EventLoop>> detection_event_loops_;
121 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
milind-u2ab4db12023-03-25 21:59:23 -0700134const auto TargetMapperReplay::kFixedTargetMapper =
135 TargetMapper(FLAGS_json_path, ceres::examples::VectorOfConstraints{});
136
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_(),
147 detectors_(),
148 vis_robot_(cv::Size(1280, 1000)),
149 drawn_nodes_(),
150 display_count_(0),
milind-u8cc03da2023-03-25 23:00:39 -0700151 last_draw_time_(aos::distributed_clock::min_time),
152 last_H_world_robot_(Eigen::Matrix4d::Identity()),
153 max_delta_T_world_robot_(0.0) {
milind-u2ab4db12023-03-25 21:59:23 -0700154 // Send new april tag poses. This allows us to take a log of images, then
155 // play with the april detection code and see those changes take effect in
156 // mapping
157 constexpr size_t kNumPis = 4;
158 for (size_t i = 1; i <= kNumPis; i++) {
159 reader_->RemapLoggedChannel(absl::StrFormat("/pi%u/camera", i),
160 "frc971.vision.TargetMap");
161 reader_->RemapLoggedChannel(absl::StrFormat("/pi%u/camera", i),
162 "foxglove.ImageAnnotations");
163 reader_->RemapLoggedChannel(absl::StrFormat("/pi%u/constants", i),
164 "y2023.Constants");
165 }
166
167 reader_->RemapLoggedChannel("/imu/constants", "y2023.Constants");
168
169 reader_->Register();
170
171 SendSimulationConstants(reader_->event_loop_factory(), FLAGS_team_number,
172 FLAGS_constants_path);
173
174 for (size_t i = 1; i < kNumPis; i++) {
175 std::string node_name = "pi" + std::to_string(i);
176 const aos::Node *pi =
177 aos::configuration::GetNode(reader_->configuration(), node_name);
178 detection_event_loops_.emplace_back(
179 reader_->event_loop_factory()->MakeEventLoop(node_name + "_detection",
180 pi));
181 mapping_event_loops_.emplace_back(
182 reader_->event_loop_factory()->MakeEventLoop(node_name + "_mapping",
183 pi));
184 HandlePiCaptures(
185 detection_event_loops_[detection_event_loops_.size() - 1].get(),
186 mapping_event_loops_[mapping_event_loops_.size() - 1].get());
187 }
188
189 if (!FLAGS_mcap_output_path.empty()) {
190 LOG(INFO) << "Writing out mcap file to " << FLAGS_mcap_output_path;
191 const aos::Node *node =
192 aos::configuration::GetNode(reader_->configuration(), FLAGS_pi);
193 reader_->event_loop_factory()->GetNodeEventLoopFactory(node)->OnStartup(
194 [this, node]() {
195 mcap_event_loop_ =
196 reader_->event_loop_factory()->MakeEventLoop("mcap", node);
197 relogger_ = std::make_unique<aos::McapLogger>(
198 mcap_event_loop_.get(), FLAGS_mcap_output_path,
199 aos::McapLogger::Serialization::kFlatbuffer,
200 aos::McapLogger::CanonicalChannelNames::kShortened,
201 aos::McapLogger::Compression::kLz4);
202 });
203 }
204
milind-u8f4e43e2023-04-09 17:11:19 -0700205 if (FLAGS_visualize_solver) {
milind-u2ab4db12023-03-25 21:59:23 -0700206 vis_robot_.ClearImage();
207 const double kFocalLength = 500.0;
208 vis_robot_.SetDefaultViewpoint(kImageWidth, kFocalLength);
209 }
210}
211
212TargetMapperReplay::~TargetMapperReplay() {
213 // Clean up all the pointers
214 for (auto &detector_ptr : detectors_) {
215 detector_ptr.reset();
216 }
217}
218
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800219// Add detected apriltag poses relative to the robot to
220// timestamped_target_detections
milind-u2ab4db12023-03-25 21:59:23 -0700221void TargetMapperReplay::HandleAprilTags(
222 const TargetMap &map,
223 aos::distributed_clock::time_point pi_distributed_time,
224 std::string node_name, Eigen::Affine3d extrinsics) {
milind-ua30a4a12023-03-24 20:49:41 -0700225 bool drew = false;
226 std::stringstream label;
227 label << node_name << " - ";
228
milind-u3f5f83c2023-01-29 15:23:51 -0800229 for (const auto *target_pose_fbs : *map.target_poses()) {
milind-ufbc5c812023-04-06 21:24:29 -0700230 // Skip detections with invalid ids
milind-u8f4e43e2023-04-09 17:11:19 -0700231 if (static_cast<TargetMapper::TargetId>(target_pose_fbs->id()) <
232 FLAGS_min_target_id ||
233 static_cast<TargetMapper::TargetId>(target_pose_fbs->id()) >
234 FLAGS_max_target_id) {
235 VLOG(1) << "Skipping tag with invalid id of " << target_pose_fbs->id();
milind-ufbc5c812023-04-06 21:24:29 -0700236 continue;
237 }
238
milind-u5ddd5152023-03-04 15:19:17 -0800239 // Skip detections with high pose errors
240 if (target_pose_fbs->pose_error() > FLAGS_max_pose_error) {
milind-u8f4e43e2023-04-09 17:11:19 -0700241 VLOG(1) << "Skipping tag " << target_pose_fbs->id()
milind-ude9045f2023-03-25 18:17:12 -0700242 << " due to pose error of " << target_pose_fbs->pose_error();
243 continue;
244 }
245 // Skip detections with high pose error ratios
246 if (target_pose_fbs->pose_error_ratio() > FLAGS_max_pose_error_ratio) {
milind-u8f4e43e2023-04-09 17:11:19 -0700247 VLOG(1) << "Skipping tag " << target_pose_fbs->id()
milind-ude9045f2023-03-25 18:17:12 -0700248 << " due to pose error ratio of "
249 << target_pose_fbs->pose_error_ratio();
milind-u5ddd5152023-03-04 15:19:17 -0800250 continue;
251 }
252
milind-u3f5f83c2023-01-29 15:23:51 -0800253 const TargetMapper::TargetPose target_pose =
254 PoseUtils::TargetPoseFromFbs(*target_pose_fbs);
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800255
milind-uee67abd2023-02-23 18:26:55 -0800256 Eigen::Affine3d H_camera_target =
milind-u3f5f83c2023-01-29 15:23:51 -0800257 Eigen::Translation3d(target_pose.pose.p) * target_pose.pose.q;
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800258 Eigen::Affine3d H_robot_target =
milind-uee67abd2023-02-23 18:26:55 -0800259 CameraToRobotDetection(H_camera_target, extrinsics);
Milind Upadhyayebf93ee2023-01-05 14:12:58 -0800260
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800261 ceres::examples::Pose3d target_pose_camera =
milind-uee67abd2023-02-23 18:26:55 -0800262 PoseUtils::Affine3dToPose3d(H_camera_target);
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800263 double distance_from_camera = target_pose_camera.p.norm();
milind-ud62f80a2023-03-04 16:37:09 -0800264 double distortion_factor = target_pose_fbs->distortion_factor();
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800265
milind-u09fb1252023-01-28 19:21:41 -0800266 CHECK(map.has_monotonic_timestamp_ns())
267 << "Need detection timestamps for mapping";
268
milind-u2ab4db12023-03-25 21:59:23 -0700269 timestamped_target_detections_.emplace_back(
Milind Upadhyayebf93ee2023-01-05 14:12:58 -0800270 DataAdapter::TimestampedDetection{
271 .time = pi_distributed_time,
272 .H_robot_target = H_robot_target,
273 .distance_from_camera = distance_from_camera,
milind-ud62f80a2023-03-04 16:37:09 -0800274 .distortion_factor = distortion_factor,
milind-u3f5f83c2023-01-29 15:23:51 -0800275 .id = static_cast<TargetMapper::TargetId>(target_pose.id)});
Jim Ostrowski49be8232023-03-23 01:00:14 -0700276
milind-u8f4e43e2023-04-09 17:11:19 -0700277 if (FLAGS_visualize_solver) {
milind-ua30a4a12023-03-24 20:49:41 -0700278 // If we've already drawn in the current image,
279 // display it before clearing and adding the new poses
milind-u2ab4db12023-03-25 21:59:23 -0700280 if (drawn_nodes_.count(node_name) != 0) {
281 display_count_++;
282 cv::putText(vis_robot_.image_,
283 "Poses #" + std::to_string(display_count_),
milind-ua30a4a12023-03-24 20:49:41 -0700284 cv::Point(600, 10), cv::FONT_HERSHEY_PLAIN, 1.0,
285 cv::Scalar(255, 255, 255));
286
milind-u2ab4db12023-03-25 21:59:23 -0700287 if (display_count_ >= FLAGS_skip_to) {
288 cv::imshow("View", vis_robot_.image_);
milind-u8cc03da2023-03-25 23:00:39 -0700289 cv::waitKey(max_delta_T_world_robot_ > FLAGS_pause_on_distance
290 ? 0
291 : FLAGS_wait_key);
292 max_delta_T_world_robot_ = 0.0;
milind-ude9045f2023-03-25 18:17:12 -0700293 } else {
milind-u2ab4db12023-03-25 21:59:23 -0700294 VLOG(1) << "At poses #" << std::to_string(display_count_);
milind-ude9045f2023-03-25 18:17:12 -0700295 }
milind-u2ab4db12023-03-25 21:59:23 -0700296 vis_robot_.ClearImage();
297 drawn_nodes_.clear();
milind-ua30a4a12023-03-24 20:49:41 -0700298 }
299
Jim Ostrowski49be8232023-03-23 01:00:14 -0700300 Eigen::Affine3d H_world_target = PoseUtils::Pose3dToAffine3d(
milind-u2ab4db12023-03-25 21:59:23 -0700301 kFixedTargetMapper.GetTargetPoseById(target_pose_fbs->id())->pose);
Jim Ostrowski49be8232023-03-23 01:00:14 -0700302 Eigen::Affine3d H_world_robot = H_world_target * H_robot_target.inverse();
milind-ude9045f2023-03-25 18:17:12 -0700303 VLOG(2) << node_name << ", " << target_pose_fbs->id()
304 << ", t = " << pi_distributed_time
305 << ", pose_error = " << target_pose_fbs->pose_error()
306 << ", pose_error_ratio = " << target_pose_fbs->pose_error_ratio()
307 << ", robot_pos (x,y,z) + "
308 << H_world_robot.translation().transpose();
milind-ua30a4a12023-03-24 20:49:41 -0700309
310 label << "id " << target_pose_fbs->id() << ": err "
milind-ude9045f2023-03-25 18:17:12 -0700311 << (target_pose_fbs->pose_error() / FLAGS_max_pose_error)
312 << " ratio " << target_pose_fbs->pose_error_ratio() << " ";
milind-ua30a4a12023-03-24 20:49:41 -0700313
milind-u2ab4db12023-03-25 21:59:23 -0700314 vis_robot_.DrawRobotOutline(H_world_robot,
milind-ua30a4a12023-03-24 20:49:41 -0700315 std::to_string(target_pose_fbs->id()),
316 kPiColors.at(node_name));
317
milind-u2ab4db12023-03-25 21:59:23 -0700318 vis_robot_.DrawFrameAxes(H_world_target,
milind-ua30a4a12023-03-24 20:49:41 -0700319 std::to_string(target_pose_fbs->id()),
320 kPiColors.at(node_name));
milind-u8cc03da2023-03-25 23:00:39 -0700321
322 double delta_T_world_robot =
323 (H_world_robot.translation() - last_H_world_robot_.translation())
324 .norm();
325 max_delta_T_world_robot_ =
326 std::max(delta_T_world_robot, max_delta_T_world_robot_);
327
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 if (drew) {
334 size_t pi_number =
335 static_cast<size_t>(node_name[node_name.size() - 1] - '0');
milind-u2ab4db12023-03-25 21:59:23 -0700336 cv::putText(vis_robot_.image_, label.str(),
milind-ua30a4a12023-03-24 20:49:41 -0700337 cv::Point(10, 10 + 20 * pi_number), cv::FONT_HERSHEY_PLAIN, 1.0,
338 kPiColors.at(node_name));
339
milind-u2ab4db12023-03-25 21:59:23 -0700340 drawn_nodes_.emplace(node_name);
341 } else if (pi_distributed_time - last_draw_time_ >
milind-u52db3362023-03-25 20:09:22 -0700342 std::chrono::milliseconds(30) &&
milind-u2ab4db12023-03-25 21:59:23 -0700343 display_count_ >= FLAGS_skip_to) {
milind-u52db3362023-03-25 20:09:22 -0700344 // Clear the image if we haven't draw in a while
milind-u2ab4db12023-03-25 21:59:23 -0700345 vis_robot_.ClearImage();
346 cv::imshow("View", vis_robot_.image_);
milind-u52db3362023-03-25 20:09:22 -0700347 cv::waitKey(FLAGS_wait_key);
milind-u8cc03da2023-03-25 23:00:39 -0700348 max_delta_T_world_robot_ = 0.0;
milind-ua30a4a12023-03-24 20:49:41 -0700349 }
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800350}
351
milind-u2ab4db12023-03-25 21:59:23 -0700352void TargetMapperReplay::HandlePiCaptures(aos::EventLoop *detection_event_loop,
353 aos::EventLoop *mapping_event_loop) {
milind-uf3ab8ba2023-02-04 17:56:16 -0800354 static constexpr std::string_view kImageChannel = "/camera";
milind-ua30a4a12023-03-24 20:49:41 -0700355 // For the robots, we need to flip the image since the cameras are rolled by
356 // 180 degrees
357 bool flip_image = (FLAGS_team_number != 7971);
milind-uf3ab8ba2023-02-04 17:56:16 -0800358 auto detector_ptr = std::make_unique<AprilRoboticsDetector>(
milind-ua30a4a12023-03-24 20:49:41 -0700359 detection_event_loop, kImageChannel, flip_image);
milind-uf2a4e322023-02-01 19:33:10 -0800360 // Get the camera extrinsics
James Kuszmaul258e4ee2023-02-23 14:22:30 -0800361 cv::Mat extrinsics_cv = detector_ptr->extrinsics().value();
milind-uf2a4e322023-02-01 19:33:10 -0800362 Eigen::Matrix4d extrinsics_matrix;
363 cv::cv2eigen(extrinsics_cv, extrinsics_matrix);
364 const auto extrinsics = Eigen::Affine3d(extrinsics_matrix);
365
milind-u2ab4db12023-03-25 21:59:23 -0700366 detectors_.emplace_back(std::move(detector_ptr));
Jim Ostrowski49be8232023-03-23 01:00:14 -0700367
milind-uf3ab8ba2023-02-04 17:56:16 -0800368 mapping_event_loop->MakeWatcher("/camera", [=](const TargetMap &map) {
milind-u09fb1252023-01-28 19:21:41 -0800369 aos::distributed_clock::time_point pi_distributed_time =
milind-u2ab4db12023-03-25 21:59:23 -0700370 reader_->event_loop_factory()
milind-uf3ab8ba2023-02-04 17:56:16 -0800371 ->GetNodeEventLoopFactory(mapping_event_loop->node())
milind-u09fb1252023-01-28 19:21:41 -0800372 ->ToDistributedClock(aos::monotonic_clock::time_point(
373 aos::monotonic_clock::duration(map.monotonic_timestamp_ns())));
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800374
Jim Ostrowski49be8232023-03-23 01:00:14 -0700375 std::string node_name = detection_event_loop->node()->name()->str();
milind-u2ab4db12023-03-25 21:59:23 -0700376 HandleAprilTags(map, pi_distributed_time, node_name, extrinsics);
milind-u09fb1252023-01-28 19:21:41 -0800377 });
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800378}
379
milind-u2ab4db12023-03-25 21:59:23 -0700380void TargetMapperReplay::MaybeSolve() {
381 if (FLAGS_solve) {
382 auto target_constraints =
383 DataAdapter::MatchTargetDetections(timestamped_target_detections_);
384
milind-ufbc5c812023-04-06 21:24:29 -0700385 // Remove constraints between the two sides of the field - these are
386 // basically garbage because of how far the camera is. We will use seeding
387 // below to connect the two sides
388 target_constraints.erase(
389 std::remove_if(target_constraints.begin(), target_constraints.end(),
390 [](const auto &constraint) {
391 constexpr TargetMapper::TargetId kMaxRedId = 4;
392 TargetMapper::TargetId min_id =
393 std::min(constraint.id_begin, constraint.id_end);
394 TargetMapper::TargetId max_id =
395 std::max(constraint.id_begin, constraint.id_end);
396 return (min_id <= kMaxRedId && max_id > kMaxRedId);
397 }),
398 target_constraints.end());
399
400 if (!FLAGS_dump_constraints_to.empty()) {
401 std::ofstream fout(FLAGS_dump_constraints_to);
402 for (const auto &constraint : target_constraints) {
403 fout << constraint << std::endl;
404 }
405 fout.flush();
406 fout.close();
407 }
408
409 // Give seed constraints with a higher confidence to ground the solver.
410 // This "distance from camera" controls the noise of the seed measurement
411 constexpr double kSeedDistanceFromCamera = 1.0;
412
413 constexpr double kSeedDistortionFactor = 0.0;
414 const DataAdapter::TimestampedDetection frozen_detection_seed = {
415 .time = aos::distributed_clock::min_time,
416 .H_robot_target = PoseUtils::Pose3dToAffine3d(
417 kFixedTargetMapper.GetTargetPoseById(FLAGS_frozen_target_id)
418 .value()
419 .pose),
420 .distance_from_camera = kSeedDistanceFromCamera,
421 .distortion_factor = kSeedDistortionFactor,
milind-u8f4e43e2023-04-09 17:11:19 -0700422 .id = FLAGS_frozen_target_id};
milind-ufbc5c812023-04-06 21:24:29 -0700423
milind-u8f4e43e2023-04-09 17:11:19 -0700424 constexpr TargetMapper::TargetId kAbsMinTargetId = 1;
425 constexpr TargetMapper::TargetId kAbsMaxTargetId = 8;
426 for (TargetMapper::TargetId id = kAbsMinTargetId; id <= kAbsMaxTargetId;
427 id++) {
428 if (id == FLAGS_frozen_target_id) {
milind-ufbc5c812023-04-06 21:24:29 -0700429 continue;
430 }
431
432 const DataAdapter::TimestampedDetection detection_seed = {
433 .time = aos::distributed_clock::min_time,
434 .H_robot_target = PoseUtils::Pose3dToAffine3d(
435 kFixedTargetMapper.GetTargetPoseById(id).value().pose),
436 .distance_from_camera = kSeedDistanceFromCamera,
437 .distortion_factor = kSeedDistortionFactor,
438 .id = id};
439 target_constraints.emplace_back(DataAdapter::ComputeTargetConstraint(
440 frozen_detection_seed, detection_seed,
441 DataAdapter::ComputeConfidence(frozen_detection_seed,
442 detection_seed)));
443 }
444
milind-u2ab4db12023-03-25 21:59:23 -0700445 TargetMapper mapper(FLAGS_json_path, target_constraints);
446 mapper.Solve(FLAGS_field_name, FLAGS_output_dir);
447 }
448}
449
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800450void MappingMain(int argc, char *argv[]) {
451 std::vector<std::string> unsorted_logfiles =
452 aos::logger::FindLogs(argc, argv);
453
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800454 std::vector<DataAdapter::TimestampedDetection> timestamped_target_detections;
455
milind-u4a5ef8a2023-03-05 14:10:23 -0800456 std::optional<aos::FlatbufferDetachedBuffer<aos::Configuration>> config =
457 (FLAGS_config.empty()
458 ? std::nullopt
459 : std::make_optional(aos::configuration::ReadConfig(FLAGS_config)));
Jim Ostrowskiaec5dd22023-02-27 22:17:53 -0800460
milind-u2ab4db12023-03-25 21:59:23 -0700461 // Open logfiles
milind-u4a5ef8a2023-03-05 14:10:23 -0800462 aos::logger::LogReader reader(
463 aos::logger::SortParts(unsorted_logfiles),
464 config.has_value() ? &config->message() : nullptr);
milind-uf3ab8ba2023-02-04 17:56:16 -0800465
milind-u2ab4db12023-03-25 21:59:23 -0700466 TargetMapperReplay mapper_replay(&reader);
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800467 reader.event_loop_factory()->Run();
milind-u2ab4db12023-03-25 21:59:23 -0700468 mapper_replay.MaybeSolve();
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800469}
470
471} // namespace vision
milind-u16e3a082023-01-21 13:53:43 -0800472} // namespace y2023
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800473
474int main(int argc, char **argv) {
475 aos::InitGoogle(&argc, &argv);
milind-u16e3a082023-01-21 13:53:43 -0800476 y2023::vision::MappingMain(argc, argv);
Milind Upadhyay915d6002022-12-26 20:37:43 -0800477}