blob: 13481b4450bbdf6d5eeea960968e5b0ce2f8198a [file] [log] [blame]
Austin Schuhdcb6b362022-02-25 18:06:21 -08001#include "frc971/vision/calibration_accumulator.h"
milind-u8c72d532021-12-11 15:02:42 -08002
Jim Ostrowskib3cab972022-12-03 15:47:00 -08003#include <algorithm>
4#include <limits>
Jim Ostrowskib3cab972022-12-03 15:47:00 -08005
milind-u8c72d532021-12-11 15:02:42 -08006#include "Eigen/Dense"
Philipp Schrader790cb542023-07-05 21:06:52 -07007#include "external/com_github_foxglove_schemas/CompressedImage_schema.h"
8#include "external/com_github_foxglove_schemas/ImageAnnotations_schema.h"
9#include <opencv2/highgui/highgui.hpp>
10
milind-u8c72d532021-12-11 15:02:42 -080011#include "aos/events/simulated_event_loop.h"
Jim Ostrowskib3cab972022-12-03 15:47:00 -080012#include "aos/network/team_number.h"
milind-u8c72d532021-12-11 15:02:42 -080013#include "aos/time/time.h"
14#include "frc971/control_loops/quaternion_utils.h"
Austin Schuhdcb6b362022-02-25 18:06:21 -080015#include "frc971/vision/charuco_lib.h"
Jim Ostrowskiba2edd12022-12-03 15:44:37 -080016#include "frc971/wpilib/imu_batch_generated.h"
17
milind-u8c72d532021-12-11 15:02:42 -080018DEFINE_bool(display_undistorted, false,
19 "If true, display the undistorted image.");
Jim Ostrowskiba2edd12022-12-03 15:44:37 -080020DEFINE_string(save_path, "", "Where to store annotated images");
21DEFINE_bool(save_valid_only, false,
22 "If true, only save images with valid pose estimates");
milind-u8c72d532021-12-11 15:02:42 -080023
Stephan Pleinesf63bde82024-01-13 15:59:33 -080024namespace frc971::vision {
milind-u8c72d532021-12-11 15:02:42 -080025using aos::distributed_clock;
26using aos::monotonic_clock;
27namespace chrono = std::chrono;
28
Austin Schuh5b379072021-12-26 16:01:04 -080029constexpr double kG = 9.807;
30
milind-u8c72d532021-12-11 15:02:42 -080031void CalibrationData::AddCameraPose(
32 distributed_clock::time_point distributed_now, Eigen::Vector3d rvec,
33 Eigen::Vector3d tvec) {
Jim Ostrowskiba2edd12022-12-03 15:44:37 -080034 // Always start with IMU (or turret) reading...
35 // Note, we may not have a turret, so need to handle that case
36 // If we later get a turret point, then we handle removal of camera points in
37 // AddTurret
38 if ((!imu_points_.empty() && imu_points_[0].first < distributed_now) &&
39 (turret_points_.empty() || turret_points_[0].first < distributed_now)) {
Austin Schuh5b379072021-12-26 16:01:04 -080040 rot_trans_points_.emplace_back(distributed_now, std::make_pair(rvec, tvec));
41 }
milind-u8c72d532021-12-11 15:02:42 -080042}
43
44void CalibrationData::AddImu(distributed_clock::time_point distributed_now,
45 Eigen::Vector3d gyro, Eigen::Vector3d accel) {
Jim Ostrowskiba2edd12022-12-03 15:44:37 -080046 double zero_threshold = 1e-12;
47 // We seem to be getting 0 readings on IMU, so ignore for now
48 // TODO<Jim>: I think this has been resolved in HandleIMU, but want to leave
49 // this here just in case there are other ways this could happen
50 if ((fabs(accel(0)) < zero_threshold) && (fabs(accel(1)) < zero_threshold) &&
51 (fabs(accel(2)) < zero_threshold)) {
52 LOG(FATAL) << "Ignoring zero value from IMU accelerometer: " << accel
53 << " (gyro is " << gyro << ")";
54 } else {
55 imu_points_.emplace_back(distributed_now, std::make_pair(gyro, accel));
56 }
milind-u8c72d532021-12-11 15:02:42 -080057}
58
Austin Schuh2895f4c2022-02-26 16:38:46 -080059void CalibrationData::AddTurret(
60 aos::distributed_clock::time_point distributed_now, Eigen::Vector2d state) {
Jim Ostrowskiba2edd12022-12-03 15:44:37 -080061 // We want the turret to be known too when solving. But, we don't know if
62 // we are going to have a turret until we get the first reading. In that
63 // case, blow away any camera readings from before.
64 // NOTE: Since the IMU motion is independent of the turret position, we don't
65 // need to remove the IMU readings before the turret
66 if (turret_points_.empty()) {
67 while (!rot_trans_points_.empty() &&
68 rot_trans_points_[0].first < distributed_now) {
69 LOG(INFO) << "Erasing, distributed " << distributed_now;
70 rot_trans_points_.erase(rot_trans_points_.begin());
71 }
Austin Schuh2895f4c2022-02-26 16:38:46 -080072 }
73 turret_points_.emplace_back(distributed_now, state);
74}
75
Austin Schuhdcb6b362022-02-25 18:06:21 -080076void CalibrationData::ReviewData(CalibrationDataObserver *observer) const {
milind-u8c72d532021-12-11 15:02:42 -080077 size_t next_camera_point = 0;
Jim Ostrowskiba2edd12022-12-03 15:44:37 -080078 size_t next_imu_point = 0;
79 size_t next_turret_point = 0;
80
81 // Just go until one of the data streams runs out. We lose a few points, but
82 // it makes the logic much easier
83 while (
84 next_camera_point != rot_trans_points_.size() &&
85 next_imu_point != imu_points_.size() &&
86 (turret_points_.empty() || next_turret_point != turret_points_.size())) {
87 // If camera_point is next, update it
88 if ((rot_trans_points_[next_camera_point].first <=
89 imu_points_[next_imu_point].first) &&
90 (turret_points_.empty() ||
91 (rot_trans_points_[next_camera_point].first <=
92 turret_points_[next_turret_point].first))) {
93 // Camera!
94 observer->UpdateCamera(rot_trans_points_[next_camera_point].first,
95 rot_trans_points_[next_camera_point].second);
96 ++next_camera_point;
97 } else {
98 // If it's not the camera, check if IMU is next
99 if (turret_points_.empty() || (imu_points_[next_imu_point].first <=
100 turret_points_[next_turret_point].first)) {
101 // IMU!
102 observer->UpdateIMU(imu_points_[next_imu_point].first,
103 imu_points_[next_imu_point].second);
104 ++next_imu_point;
milind-u8c72d532021-12-11 15:02:42 -0800105 } else {
Jim Ostrowskiba2edd12022-12-03 15:44:37 -0800106 // If it's not IMU or camera, and turret_points is not empty, it must be
107 // the turret!
108 observer->UpdateTurret(turret_points_[next_turret_point].first,
109 turret_points_[next_turret_point].second);
110 ++next_turret_point;
milind-u8c72d532021-12-11 15:02:42 -0800111 }
112 }
113 }
114}
115
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800116CalibrationFoxgloveVisualizer::CalibrationFoxgloveVisualizer(
Maxwell Hendersonecc8a7c2024-02-29 20:19:45 -0800117 aos::EventLoop *event_loop, std::string_view camera_channel)
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800118 : event_loop_(event_loop),
Maxwell Hendersonecc8a7c2024-02-29 20:19:45 -0800119 image_converter_(event_loop_, camera_channel, camera_channel,
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800120 ImageCompression::kJpeg),
121 annotations_sender_(
Maxwell Hendersonecc8a7c2024-02-29 20:19:45 -0800122 event_loop_->MakeSender<foxglove::ImageAnnotations>(camera_channel)) {
123}
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800124
125aos::FlatbufferDetachedBuffer<aos::Configuration>
126CalibrationFoxgloveVisualizer::AddVisualizationChannels(
127 const aos::Configuration *config, const aos::Node *node) {
128 constexpr std::string_view channel_name = "/visualization";
129 aos::ChannelT channel_overrides;
130 channel_overrides.max_size = 10000000;
131 aos::FlatbufferDetachedBuffer<aos::Configuration> result =
132 aos::configuration::AddChannelToConfiguration(
133 config, channel_name,
134 aos::FlatbufferSpan<reflection::Schema>(
135 foxglove::ImageAnnotationsSchema()),
136 node, channel_overrides);
137 return aos::configuration::AddChannelToConfiguration(
138 &result.message(), channel_name,
139 aos::FlatbufferSpan<reflection::Schema>(
140 foxglove::CompressedImageSchema()),
141 node, channel_overrides);
142}
143
James Kuszmaul7e958812023-02-11 15:34:31 -0800144Calibration::Calibration(
145 aos::SimulatedEventLoopFactory *event_loop_factory,
146 aos::EventLoop *image_event_loop, aos::EventLoop *imu_event_loop,
Jim Ostrowski3dc21642024-01-22 16:08:40 -0800147 std::string_view hostname,
James Kuszmaul7e958812023-02-11 15:34:31 -0800148 const calibration::CameraCalibration *intrinsics_calibration,
149 TargetType target_type, std::string_view image_channel,
150 CalibrationData *data)
milind-u8c72d532021-12-11 15:02:42 -0800151 : image_event_loop_(image_event_loop),
152 image_factory_(event_loop_factory->GetNodeEventLoopFactory(
153 image_event_loop_->node())),
154 imu_event_loop_(imu_event_loop),
155 imu_factory_(
156 event_loop_factory->GetNodeEventLoopFactory(imu_event_loop_->node())),
157 charuco_extractor_(
James Kuszmaul7e958812023-02-11 15:34:31 -0800158 image_event_loop_, intrinsics_calibration, target_type, image_channel,
milind-u8c72d532021-12-11 15:02:42 -0800159 [this](cv::Mat rgb_image, monotonic_clock::time_point eof,
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800160 std::vector<cv::Vec4i> charuco_ids,
161 std::vector<std::vector<cv::Point2f>> charuco_corners,
162 bool valid, std::vector<Eigen::Vector3d> rvecs_eigen,
163 std::vector<Eigen::Vector3d> tvecs_eigen) {
milind-u8c72d532021-12-11 15:02:42 -0800164 HandleCharuco(rgb_image, eof, charuco_ids, charuco_corners, valid,
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800165 rvecs_eigen, tvecs_eigen);
166 }),
Jim Ostrowskicb8b4082024-01-21 02:23:46 -0800167 // TODO: Need to make this work for pi or orin
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800168 image_callback_(
169 image_event_loop_,
Jim Ostrowski3dc21642024-01-22 16:08:40 -0800170 absl::StrCat("/", aos::network::ParsePiOrOrin(hostname).value(),
171 std::to_string(
172 aos::network::ParsePiOrOrinNumber(hostname).value()),
173 image_channel),
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800174 [this](cv::Mat rgb_image, const monotonic_clock::time_point eof) {
175 charuco_extractor_.HandleImage(rgb_image, eof);
milind-u8c72d532021-12-11 15:02:42 -0800176 }),
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800177 data_(data),
178 visualizer_event_loop_(image_factory_->MakeEventLoop("visualization")),
Maxwell Hendersonecc8a7c2024-02-29 20:19:45 -0800179 visualizer_(visualizer_event_loop_.get(), image_channel) {
milind-u8c72d532021-12-11 15:02:42 -0800180 imu_factory_->OnShutdown([]() { cv::destroyAllWindows(); });
181
Jim Ostrowskiba2edd12022-12-03 15:44:37 -0800182 // Check for IMUValuesBatch topic on both /localizer and /drivetrain channels,
183 // since both are valid/possible
184 std::string imu_channel;
185 if (imu_event_loop->HasChannel<frc971::IMUValuesBatch>("/localizer")) {
186 imu_channel = "/localizer";
187 } else if (imu_event_loop->HasChannel<frc971::IMUValuesBatch>(
188 "/drivetrain")) {
189 imu_channel = "/drivetrain";
190 } else {
191 LOG(FATAL) << "Couldn't find channel with IMU data for either localizer or "
192 "drivtrain";
193 }
194
195 VLOG(2) << "Listening for " << frc971::IMUValuesBatch::GetFullyQualifiedName()
196 << " on channel: " << imu_channel;
197
milind-u8c72d532021-12-11 15:02:42 -0800198 imu_event_loop_->MakeWatcher(
Jim Ostrowskiba2edd12022-12-03 15:44:37 -0800199 imu_channel, [this](const frc971::IMUValuesBatch &imu) {
milind-u8c72d532021-12-11 15:02:42 -0800200 if (!imu.has_readings()) {
201 return;
202 }
203 for (const frc971::IMUValues *value : *imu.readings()) {
204 HandleIMU(value);
205 }
206 });
207}
208
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800209void Calibration::HandleCharuco(
210 cv::Mat rgb_image, const monotonic_clock::time_point eof,
211 std::vector<cv::Vec4i> /*charuco_ids*/,
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800212 std::vector<std::vector<cv::Point2f>> charuco_corners, bool valid,
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800213 std::vector<Eigen::Vector3d> rvecs_eigen,
214 std::vector<Eigen::Vector3d> tvecs_eigen) {
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800215 visualizer_.HandleCharuco(eof, charuco_corners);
milind-u8c72d532021-12-11 15:02:42 -0800216 if (valid) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800217 CHECK(rvecs_eigen.size() > 0) << "Require at least one target detected";
218 // We only use one (the first) target detected for calibration
219 data_->AddCameraPose(image_factory_->ToDistributedClock(eof),
220 rvecs_eigen[0], tvecs_eigen[0]);
milind-u8c72d532021-12-11 15:02:42 -0800221
milind-u8c72d532021-12-11 15:02:42 -0800222 Eigen::IOFormat HeavyFmt(Eigen::FullPrecision, 0, ", ", ",\n", "[", "]",
223 "[", "]");
224
225 const double age_double =
226 std::chrono::duration_cast<std::chrono::duration<double>>(
227 image_event_loop_->monotonic_now() - eof)
228 .count();
Jim Ostrowskiba2edd12022-12-03 15:44:37 -0800229 VLOG(1) << std::fixed << std::setprecision(6) << "Age: " << age_double
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800230 << ", Pose is R:" << rvecs_eigen[0].transpose().format(HeavyFmt)
231 << "\nT:" << tvecs_eigen[0].transpose().format(HeavyFmt);
milind-u8c72d532021-12-11 15:02:42 -0800232 }
233
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800234 if (FLAGS_visualize) {
235 if (FLAGS_display_undistorted) {
236 const cv::Size image_size(rgb_image.cols, rgb_image.rows);
237 cv::Mat undistorted_rgb_image(image_size, CV_8UC3);
238 cv::undistort(rgb_image, undistorted_rgb_image,
239 charuco_extractor_.camera_matrix(),
240 charuco_extractor_.dist_coeffs());
milind-u8c72d532021-12-11 15:02:42 -0800241
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800242 cv::imshow("Display undist", undistorted_rgb_image);
243 }
milind-u8c72d532021-12-11 15:02:42 -0800244
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800245 cv::imshow("Display", rgb_image);
246 cv::waitKey(1);
milind-u8c72d532021-12-11 15:02:42 -0800247 }
Jim Ostrowskiba2edd12022-12-03 15:44:37 -0800248
249 if (FLAGS_save_path != "") {
250 if (!FLAGS_save_valid_only || valid) {
251 static int img_count = 0;
252 std::string image_name = absl::StrFormat("/img_%06d.png", img_count);
253 std::string path = FLAGS_save_path + image_name;
254 VLOG(2) << "Saving image to " << path;
255 cv::imwrite(path, rgb_image);
256 img_count++;
257 }
258 }
milind-u8c72d532021-12-11 15:02:42 -0800259}
260
261void Calibration::HandleIMU(const frc971::IMUValues *imu) {
Jim Ostrowskiba2edd12022-12-03 15:44:37 -0800262 // Need to check for valid values, since we sometimes don't get them
263 if (!imu->has_gyro_x() || !imu->has_gyro_y() || !imu->has_gyro_z() ||
264 !imu->has_accelerometer_x() || !imu->has_accelerometer_y() ||
265 !imu->has_accelerometer_z()) {
266 return;
267 }
268
269 VLOG(2) << "IMU " << imu;
milind-u8c72d532021-12-11 15:02:42 -0800270 imu->UnPackTo(&last_value_);
271 Eigen::Vector3d gyro(last_value_.gyro_x, last_value_.gyro_y,
272 last_value_.gyro_z);
273 Eigen::Vector3d accel(last_value_.accelerometer_x,
274 last_value_.accelerometer_y,
275 last_value_.accelerometer_z);
276
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800277 // TODO: ToDistributedClock may be too noisy.
milind-u8c72d532021-12-11 15:02:42 -0800278 data_->AddImu(imu_factory_->ToDistributedClock(monotonic_clock::time_point(
279 chrono::nanoseconds(imu->monotonic_timestamp_ns()))),
Austin Schuh5b379072021-12-26 16:01:04 -0800280 gyro, accel * kG);
milind-u8c72d532021-12-11 15:02:42 -0800281}
282
Stephan Pleinesf63bde82024-01-13 15:59:33 -0800283} // namespace frc971::vision