blob: 090ac60f0e7b488d4d70133f838c83517a58166e [file] [log] [blame]
Yash Chainanid5c7f0d2022-11-19 17:05:57 -08001#include "aos/events/logging/log_reader.h"
2#include "aos/events/simulated_event_loop.h"
3#include "aos/init.h"
4#include "frc971/control_loops/pose.h"
5#include "frc971/vision/charuco_lib.h"
6#include "frc971/vision/target_mapper.h"
7#include "opencv2/aruco.hpp"
8#include "opencv2/calib3d.hpp"
9#include "opencv2/core/eigen.hpp"
10#include "opencv2/features2d.hpp"
11#include "opencv2/highgui.hpp"
12#include "opencv2/highgui/highgui.hpp"
13#include "opencv2/imgproc.hpp"
14#include "y2022/control_loops/superstructure/superstructure_status_generated.h"
15#include "y2022/vision/camera_reader.h"
16
17DEFINE_string(json_path, "target_map.json",
18 "Specify path for json with initial pose guesses.");
Milind Upadhyay915d6002022-12-26 20:37:43 -080019DEFINE_int32(team_number, 971,
20 "Use the calibration for a node with this team number");
21
22DEFINE_bool(
23 use_robot_position, false,
24 "If true, use localizer output messages to get the robot position, and "
25 "superstructure status messages to get the turret angle, at the "
26 "times of target detections. Currently does not work reliably on the box "
27 "of pis.");
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080028
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -080029DECLARE_string(image_channel);
30
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080031namespace y2022 {
32namespace vision {
33using frc971::vision::DataAdapter;
34using frc971::vision::PoseUtils;
35using frc971::vision::TargetMapper;
36namespace superstructure = ::y2022::control_loops::superstructure;
37
38// Find transformation from camera to robot reference frame
39Eigen::Affine3d CameraTransform(Eigen::Affine3d fixed_extrinsics,
40 Eigen::Affine3d turret_extrinsics,
41 double turret_position) {
42 // Calculate the pose of the camera relative to the robot origin.
43 Eigen::Affine3d H_robot_camrob =
44 fixed_extrinsics *
45 Eigen::Affine3d(frc971::control_loops::TransformationMatrixForYaw<double>(
46 turret_position)) *
47 turret_extrinsics;
48
49 return H_robot_camrob;
50}
51
52// Change reference frame from camera to robot
Milind Upadhyayebf93ee2023-01-05 14:12:58 -080053Eigen::Affine3d CameraToRobotDetection(Eigen::Affine3d H_camrob_target,
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080054 Eigen::Affine3d fixed_extrinsics,
55 Eigen::Affine3d turret_extrinsics,
56 double turret_position) {
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080057 const Eigen::Affine3d H_robot_camrob =
58 CameraTransform(fixed_extrinsics, turret_extrinsics, turret_position);
Milind Upadhyayebf93ee2023-01-05 14:12:58 -080059 const Eigen::Affine3d H_robot_target = H_robot_camrob * H_camrob_target;
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080060 return H_robot_target;
61}
62
63// Add detected apriltag poses relative to the robot to
64// timestamped_target_detections
Milind Upadhyay915d6002022-12-26 20:37:43 -080065void HandleAprilTag(aos::distributed_clock::time_point pi_distributed_time,
66 std::vector<cv::Vec4i> april_ids,
67 std::vector<Eigen::Vector3d> rvecs_eigen,
68 std::vector<Eigen::Vector3d> tvecs_eigen,
69 std::vector<DataAdapter::TimestampedDetection>
70 *timestamped_target_detections,
71 std::optional<aos::Fetcher<superstructure::Status>>
72 *superstructure_status_fetcher,
73 Eigen::Affine3d fixed_extrinsics,
74 Eigen::Affine3d turret_extrinsics) {
75 double turret_position = 0.0;
76
77 if (superstructure_status_fetcher->has_value()) {
78 CHECK(superstructure_status_fetcher->value().Fetch());
79 turret_position =
80 superstructure_status_fetcher->value().get()->turret()->position();
81 }
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080082
83 for (size_t tag = 0; tag < april_ids.size(); tag++) {
84 Eigen::Translation3d T_camera_target = Eigen::Translation3d(
85 tvecs_eigen[tag][0], tvecs_eigen[tag][1], tvecs_eigen[tag][2]);
86 Eigen::AngleAxisd r_angle = Eigen::AngleAxisd(
87 rvecs_eigen[tag].norm(), rvecs_eigen[tag] / rvecs_eigen[tag].norm());
88 CHECK(rvecs_eigen[tag].norm() != 0) << "rvecs norm = 0; divide by 0";
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080089
Milind Upadhyayebf93ee2023-01-05 14:12:58 -080090 Eigen::Affine3d H_camcv_target = T_camera_target * r_angle;
91 // With X, Y, Z being robot axes and x, y, z being camera axes,
92 // x = -Y, y = -Z, z = X
93 static const Eigen::Affine3d H_camcv_camrob =
94 Eigen::Affine3d((Eigen::Matrix4d() << 0.0, -1.0, 0.0, 0.0, 0.0, 0.0,
95 -1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)
96 .finished());
97 Eigen::Affine3d H_camrob_target = H_camcv_camrob.inverse() * H_camcv_target;
Yash Chainanid5c7f0d2022-11-19 17:05:57 -080098 Eigen::Affine3d H_robot_target = CameraToRobotDetection(
Milind Upadhyayebf93ee2023-01-05 14:12:58 -080099 H_camrob_target, fixed_extrinsics, turret_extrinsics, turret_position);
100
101 ceres::examples::Pose2d target_pose_camera =
102 PoseUtils::Affine3dToPose2d(H_camrob_target);
103 double distance_from_camera = std::sqrt(std::pow(target_pose_camera.x, 2) +
104 std::pow(target_pose_camera.y, 2));
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800105
106 timestamped_target_detections->emplace_back(
Milind Upadhyayebf93ee2023-01-05 14:12:58 -0800107 DataAdapter::TimestampedDetection{
108 .time = pi_distributed_time,
109 .H_robot_target = H_robot_target,
110 .distance_from_camera = distance_from_camera,
111 .id = april_ids[tag][0]});
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800112 }
113}
114
115Eigen::Affine3d CameraFixedExtrinsics(
116 const calibration::CameraCalibration *camera_calibration) {
117 cv::Mat extrinsics(
118 4, 4, CV_32F,
119 const_cast<void *>(static_cast<const void *>(
120 camera_calibration->fixed_extrinsics()->data()->data())));
121 extrinsics.convertTo(extrinsics, CV_64F);
122 CHECK_EQ(extrinsics.total(),
123 camera_calibration->fixed_extrinsics()->data()->size());
124 Eigen::Matrix4d extrinsics_eigen;
125 cv::cv2eigen(extrinsics, extrinsics_eigen);
126 return Eigen::Affine3d(extrinsics_eigen);
127}
128
129Eigen::Affine3d CameraTurretExtrinsics(
130 const calibration::CameraCalibration *camera_calibration) {
131 cv::Mat extrinsics(
132 4, 4, CV_32F,
133 const_cast<void *>(static_cast<const void *>(
134 camera_calibration->turret_extrinsics()->data()->data())));
135 extrinsics.convertTo(extrinsics, CV_64F);
136 CHECK_EQ(extrinsics.total(),
137 camera_calibration->turret_extrinsics()->data()->size());
138 Eigen::Matrix4d extrinsics_eigen;
139 cv::cv2eigen(extrinsics, extrinsics_eigen);
140 return Eigen::Affine3d(extrinsics_eigen);
141}
142
143// Get images from pi and pass apriltag positions to HandleAprilTag()
144void HandlePiCaptures(
145 int pi_number, aos::EventLoop *pi_event_loop,
146 aos::logger::LogReader *reader,
Milind Upadhyay915d6002022-12-26 20:37:43 -0800147 std::optional<aos::Fetcher<superstructure::Status>>
148 *superstructure_status_fetcher,
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800149 std::vector<DataAdapter::TimestampedDetection>
150 *timestamped_target_detections,
151 std::vector<std::unique_ptr<CharucoExtractor>> *charuco_extractors,
152 std::vector<std::unique_ptr<ImageCallback>> *image_callbacks) {
153 const aos::FlatbufferSpan<calibration::CalibrationData> calibration_data(
154 CalibrationData());
155 const calibration::CameraCalibration *calibration =
156 CameraReader::FindCameraCalibration(&calibration_data.message(),
157 "pi" + std::to_string(pi_number),
158 FLAGS_team_number);
159 const auto turret_extrinsics = CameraTurretExtrinsics(calibration);
160 const auto fixed_extrinsics = CameraFixedExtrinsics(calibration);
161
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800162 // TODO(milind): change to /camera once we log at full frequency
163 static constexpr std::string_view kImageChannel = "/camera/decimated";
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800164 charuco_extractors->emplace_back(std::make_unique<CharucoExtractor>(
165 pi_event_loop,
166 "pi-" + std::to_string(FLAGS_team_number) + "-" +
167 std::to_string(pi_number),
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800168 TargetType::kAprilTag, kImageChannel,
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800169 [=](cv::Mat /*rgb_image*/, aos::monotonic_clock::time_point eof,
170 std::vector<cv::Vec4i> april_ids,
171 std::vector<std::vector<cv::Point2f>> /*april_corners*/, bool valid,
172 std::vector<Eigen::Vector3d> rvecs_eigen,
173 std::vector<Eigen::Vector3d> tvecs_eigen) {
174 aos::distributed_clock::time_point pi_distributed_time =
175 reader->event_loop_factory()
176 ->GetNodeEventLoopFactory(pi_event_loop->node())
177 ->ToDistributedClock(eof);
178
179 if (valid) {
180 HandleAprilTag(pi_distributed_time, april_ids, rvecs_eigen,
181 tvecs_eigen, timestamped_target_detections,
182 superstructure_status_fetcher, fixed_extrinsics,
183 turret_extrinsics);
184 }
185 }));
186
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800187 image_callbacks->emplace_back(std::make_unique<ImageCallback>(
Milind Upadhyayc6e42ee2022-12-27 00:02:11 -0800188 pi_event_loop, kImageChannel,
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800189 [&, charuco_extractor =
190 charuco_extractors->at(charuco_extractors->size() - 1).get()](
191 cv::Mat rgb_image, const aos::monotonic_clock::time_point eof) {
192 charuco_extractor->HandleImage(rgb_image, eof);
193 }));
194}
195
196void MappingMain(int argc, char *argv[]) {
197 std::vector<std::string> unsorted_logfiles =
198 aos::logger::FindLogs(argc, argv);
199
200 std::vector<DataAdapter::TimestampedPose> timestamped_robot_poses;
201 std::vector<DataAdapter::TimestampedDetection> timestamped_target_detections;
202
203 // open logfiles
204 aos::logger::LogReader reader(aos::logger::SortParts(unsorted_logfiles));
205 reader.Register();
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800206
Milind Upadhyay915d6002022-12-26 20:37:43 -0800207 std::optional<aos::Fetcher<superstructure::Status>>
208 superstructure_status_fetcher;
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800209
Milind Upadhyay915d6002022-12-26 20:37:43 -0800210 if (FLAGS_use_robot_position) {
211 const aos::Node *imu_node =
212 aos::configuration::GetNode(reader.configuration(), "imu");
213 std::unique_ptr<aos::EventLoop> imu_event_loop =
214 reader.event_loop_factory()->MakeEventLoop("imu", imu_node);
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800215
Milind Upadhyay915d6002022-12-26 20:37:43 -0800216 imu_event_loop->MakeWatcher(
217 "/localizer", [&](const frc971::controls::LocalizerOutput &localizer) {
218 aos::monotonic_clock::time_point imu_monotonic_time =
219 aos::monotonic_clock::time_point(aos::monotonic_clock::duration(
220 localizer.monotonic_timestamp_ns()));
221 aos::distributed_clock::time_point imu_distributed_time =
222 reader.event_loop_factory()
223 ->GetNodeEventLoopFactory(imu_node)
224 ->ToDistributedClock(imu_monotonic_time);
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800225
Milind Upadhyay915d6002022-12-26 20:37:43 -0800226 timestamped_robot_poses.emplace_back(DataAdapter::TimestampedPose{
227 .time = imu_distributed_time,
228 .pose =
229 ceres::examples::Pose2d{.x = localizer.x(),
230 .y = localizer.y(),
231 .yaw_radians = localizer.theta()}});
232 });
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800233
Milind Upadhyay915d6002022-12-26 20:37:43 -0800234 const aos::Node *roborio_node =
235 aos::configuration::GetNode(reader.configuration(), "roborio");
236 std::unique_ptr<aos::EventLoop> roborio_event_loop =
237 reader.event_loop_factory()->MakeEventLoop("roborio", roborio_node);
238
239 superstructure_status_fetcher =
240 roborio_event_loop->MakeFetcher<superstructure::Status>(
241 "/superstructure");
242 }
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800243
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800244 std::vector<std::unique_ptr<CharucoExtractor>> charuco_extractors;
245 std::vector<std::unique_ptr<ImageCallback>> image_callbacks;
246
247 const aos::Node *pi1 =
248 aos::configuration::GetNode(reader.configuration(), "pi1");
249 std::unique_ptr<aos::EventLoop> pi1_event_loop =
250 reader.event_loop_factory()->MakeEventLoop("pi1", pi1);
251 HandlePiCaptures(
252 1, pi1_event_loop.get(), &reader, &superstructure_status_fetcher,
253 &timestamped_target_detections, &charuco_extractors, &image_callbacks);
254
255 const aos::Node *pi2 =
256 aos::configuration::GetNode(reader.configuration(), "pi2");
257 std::unique_ptr<aos::EventLoop> pi2_event_loop =
258 reader.event_loop_factory()->MakeEventLoop("pi2", pi2);
259 HandlePiCaptures(
260 2, pi2_event_loop.get(), &reader, &superstructure_status_fetcher,
261 &timestamped_target_detections, &charuco_extractors, &image_callbacks);
262
263 const aos::Node *pi3 =
264 aos::configuration::GetNode(reader.configuration(), "pi3");
265 std::unique_ptr<aos::EventLoop> pi3_event_loop =
266 reader.event_loop_factory()->MakeEventLoop("pi3", pi3);
267 HandlePiCaptures(
268 3, pi3_event_loop.get(), &reader, &superstructure_status_fetcher,
269 &timestamped_target_detections, &charuco_extractors, &image_callbacks);
270
271 const aos::Node *pi4 =
272 aos::configuration::GetNode(reader.configuration(), "pi4");
273 std::unique_ptr<aos::EventLoop> pi4_event_loop =
274 reader.event_loop_factory()->MakeEventLoop("pi4", pi4);
275 HandlePiCaptures(
276 4, pi4_event_loop.get(), &reader, &superstructure_status_fetcher,
277 &timestamped_target_detections, &charuco_extractors, &image_callbacks);
278
279 reader.event_loop_factory()->Run();
280
281 auto target_constraints =
Milind Upadhyay915d6002022-12-26 20:37:43 -0800282 (FLAGS_use_robot_position
283 ? DataAdapter::MatchTargetDetections(timestamped_robot_poses,
284 timestamped_target_detections)
285 .first
286 : DataAdapter::MatchTargetDetections(timestamped_target_detections));
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800287
288 frc971::vision::TargetMapper mapper(FLAGS_json_path, target_constraints);
Yash Chainani03669632022-12-17 19:37:34 -0800289 mapper.Solve("rapid_react");
Yash Chainanid5c7f0d2022-11-19 17:05:57 -0800290
291 // Pointers need to be deleted to destruct all fetchers
292 for (auto &charuco_extractor_ptr : charuco_extractors) {
293 charuco_extractor_ptr.reset();
294 }
295
296 for (auto &image_callback_ptr : image_callbacks) {
297 image_callback_ptr.reset();
298 }
299}
300
301} // namespace vision
302} // namespace y2022
303
304int main(int argc, char **argv) {
305 aos::InitGoogle(&argc, &argv);
306 y2022::vision::MappingMain(argc, argv);
Milind Upadhyay915d6002022-12-26 20:37:43 -0800307}