blob: bbf51eedf404d9572ff03e1b9aca42d7dcf61d94 [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>
Stephan Pleines6191f1d2024-05-30 20:44:45 -07004#include <iomanip>
Jim Ostrowskib3cab972022-12-03 15:47:00 -08005#include <limits>
Jim Ostrowskib3cab972022-12-03 15:47:00 -08006
milind-u8c72d532021-12-11 15:02:42 -08007#include "Eigen/Dense"
Philipp Schrader790cb542023-07-05 21:06:52 -07008#include "external/com_github_foxglove_schemas/CompressedImage_schema.h"
9#include "external/com_github_foxglove_schemas/ImageAnnotations_schema.h"
10#include <opencv2/highgui/highgui.hpp>
11
milind-u8c72d532021-12-11 15:02:42 -080012#include "aos/events/simulated_event_loop.h"
Jim Ostrowskib3cab972022-12-03 15:47:00 -080013#include "aos/network/team_number.h"
milind-u8c72d532021-12-11 15:02:42 -080014#include "aos/time/time.h"
15#include "frc971/control_loops/quaternion_utils.h"
Austin Schuhdcb6b362022-02-25 18:06:21 -080016#include "frc971/vision/charuco_lib.h"
Jim Ostrowskiba2edd12022-12-03 15:44:37 -080017#include "frc971/wpilib/imu_batch_generated.h"
18
milind-u8c72d532021-12-11 15:02:42 -080019DEFINE_bool(display_undistorted, false,
20 "If true, display the undistorted image.");
Jim Ostrowskiba2edd12022-12-03 15:44:37 -080021DEFINE_string(save_path, "", "Where to store annotated images");
22DEFINE_bool(save_valid_only, false,
23 "If true, only save images with valid pose estimates");
milind-u8c72d532021-12-11 15:02:42 -080024
Stephan Pleinesf63bde82024-01-13 15:59:33 -080025namespace frc971::vision {
milind-u8c72d532021-12-11 15:02:42 -080026using aos::distributed_clock;
27using aos::monotonic_clock;
28namespace chrono = std::chrono;
29
Austin Schuh5b379072021-12-26 16:01:04 -080030constexpr double kG = 9.807;
31
milind-u8c72d532021-12-11 15:02:42 -080032void CalibrationData::AddCameraPose(
33 distributed_clock::time_point distributed_now, Eigen::Vector3d rvec,
34 Eigen::Vector3d tvec) {
Jim Ostrowskiba2edd12022-12-03 15:44:37 -080035 // Always start with IMU (or turret) reading...
36 // Note, we may not have a turret, so need to handle that case
37 // If we later get a turret point, then we handle removal of camera points in
38 // AddTurret
39 if ((!imu_points_.empty() && imu_points_[0].first < distributed_now) &&
40 (turret_points_.empty() || turret_points_[0].first < distributed_now)) {
Austin Schuh5b379072021-12-26 16:01:04 -080041 rot_trans_points_.emplace_back(distributed_now, std::make_pair(rvec, tvec));
42 }
milind-u8c72d532021-12-11 15:02:42 -080043}
44
45void CalibrationData::AddImu(distributed_clock::time_point distributed_now,
46 Eigen::Vector3d gyro, Eigen::Vector3d accel) {
Jim Ostrowskiba2edd12022-12-03 15:44:37 -080047 double zero_threshold = 1e-12;
48 // We seem to be getting 0 readings on IMU, so ignore for now
49 // TODO<Jim>: I think this has been resolved in HandleIMU, but want to leave
50 // this here just in case there are other ways this could happen
51 if ((fabs(accel(0)) < zero_threshold) && (fabs(accel(1)) < zero_threshold) &&
52 (fabs(accel(2)) < zero_threshold)) {
53 LOG(FATAL) << "Ignoring zero value from IMU accelerometer: " << accel
54 << " (gyro is " << gyro << ")";
55 } else {
56 imu_points_.emplace_back(distributed_now, std::make_pair(gyro, accel));
57 }
milind-u8c72d532021-12-11 15:02:42 -080058}
59
Austin Schuh2895f4c2022-02-26 16:38:46 -080060void CalibrationData::AddTurret(
61 aos::distributed_clock::time_point distributed_now, Eigen::Vector2d state) {
Jim Ostrowskiba2edd12022-12-03 15:44:37 -080062 // We want the turret to be known too when solving. But, we don't know if
63 // we are going to have a turret until we get the first reading. In that
64 // case, blow away any camera readings from before.
65 // NOTE: Since the IMU motion is independent of the turret position, we don't
66 // need to remove the IMU readings before the turret
67 if (turret_points_.empty()) {
68 while (!rot_trans_points_.empty() &&
69 rot_trans_points_[0].first < distributed_now) {
70 LOG(INFO) << "Erasing, distributed " << distributed_now;
71 rot_trans_points_.erase(rot_trans_points_.begin());
72 }
Austin Schuh2895f4c2022-02-26 16:38:46 -080073 }
74 turret_points_.emplace_back(distributed_now, state);
75}
76
Austin Schuhdcb6b362022-02-25 18:06:21 -080077void CalibrationData::ReviewData(CalibrationDataObserver *observer) const {
milind-u8c72d532021-12-11 15:02:42 -080078 size_t next_camera_point = 0;
Jim Ostrowskiba2edd12022-12-03 15:44:37 -080079 size_t next_imu_point = 0;
80 size_t next_turret_point = 0;
81
82 // Just go until one of the data streams runs out. We lose a few points, but
83 // it makes the logic much easier
84 while (
85 next_camera_point != rot_trans_points_.size() &&
86 next_imu_point != imu_points_.size() &&
87 (turret_points_.empty() || next_turret_point != turret_points_.size())) {
88 // If camera_point is next, update it
89 if ((rot_trans_points_[next_camera_point].first <=
90 imu_points_[next_imu_point].first) &&
91 (turret_points_.empty() ||
92 (rot_trans_points_[next_camera_point].first <=
93 turret_points_[next_turret_point].first))) {
94 // Camera!
95 observer->UpdateCamera(rot_trans_points_[next_camera_point].first,
96 rot_trans_points_[next_camera_point].second);
97 ++next_camera_point;
98 } else {
99 // If it's not the camera, check if IMU is next
100 if (turret_points_.empty() || (imu_points_[next_imu_point].first <=
101 turret_points_[next_turret_point].first)) {
102 // IMU!
103 observer->UpdateIMU(imu_points_[next_imu_point].first,
104 imu_points_[next_imu_point].second);
105 ++next_imu_point;
milind-u8c72d532021-12-11 15:02:42 -0800106 } else {
Jim Ostrowskiba2edd12022-12-03 15:44:37 -0800107 // If it's not IMU or camera, and turret_points is not empty, it must be
108 // the turret!
109 observer->UpdateTurret(turret_points_[next_turret_point].first,
110 turret_points_[next_turret_point].second);
111 ++next_turret_point;
milind-u8c72d532021-12-11 15:02:42 -0800112 }
113 }
114 }
115}
116
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800117CalibrationFoxgloveVisualizer::CalibrationFoxgloveVisualizer(
Maxwell Hendersonecc8a7c2024-02-29 20:19:45 -0800118 aos::EventLoop *event_loop, std::string_view camera_channel)
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800119 : event_loop_(event_loop),
Maxwell Hendersonecc8a7c2024-02-29 20:19:45 -0800120 image_converter_(event_loop_, camera_channel, camera_channel,
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800121 ImageCompression::kJpeg),
122 annotations_sender_(
Maxwell Hendersonecc8a7c2024-02-29 20:19:45 -0800123 event_loop_->MakeSender<foxglove::ImageAnnotations>(camera_channel)) {
124}
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800125
126aos::FlatbufferDetachedBuffer<aos::Configuration>
127CalibrationFoxgloveVisualizer::AddVisualizationChannels(
128 const aos::Configuration *config, const aos::Node *node) {
129 constexpr std::string_view channel_name = "/visualization";
130 aos::ChannelT channel_overrides;
131 channel_overrides.max_size = 10000000;
132 aos::FlatbufferDetachedBuffer<aos::Configuration> result =
133 aos::configuration::AddChannelToConfiguration(
134 config, channel_name,
135 aos::FlatbufferSpan<reflection::Schema>(
136 foxglove::ImageAnnotationsSchema()),
137 node, channel_overrides);
138 return aos::configuration::AddChannelToConfiguration(
139 &result.message(), channel_name,
140 aos::FlatbufferSpan<reflection::Schema>(
141 foxglove::CompressedImageSchema()),
142 node, channel_overrides);
143}
144
James Kuszmaul7e958812023-02-11 15:34:31 -0800145Calibration::Calibration(
146 aos::SimulatedEventLoopFactory *event_loop_factory,
147 aos::EventLoop *image_event_loop, aos::EventLoop *imu_event_loop,
Jim Ostrowski3dc21642024-01-22 16:08:40 -0800148 std::string_view hostname,
James Kuszmaul7e958812023-02-11 15:34:31 -0800149 const calibration::CameraCalibration *intrinsics_calibration,
150 TargetType target_type, std::string_view image_channel,
151 CalibrationData *data)
milind-u8c72d532021-12-11 15:02:42 -0800152 : image_event_loop_(image_event_loop),
153 image_factory_(event_loop_factory->GetNodeEventLoopFactory(
154 image_event_loop_->node())),
155 imu_event_loop_(imu_event_loop),
156 imu_factory_(
157 event_loop_factory->GetNodeEventLoopFactory(imu_event_loop_->node())),
158 charuco_extractor_(
James Kuszmaul7e958812023-02-11 15:34:31 -0800159 image_event_loop_, intrinsics_calibration, target_type, image_channel,
milind-u8c72d532021-12-11 15:02:42 -0800160 [this](cv::Mat rgb_image, monotonic_clock::time_point eof,
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800161 std::vector<cv::Vec4i> charuco_ids,
162 std::vector<std::vector<cv::Point2f>> charuco_corners,
163 bool valid, std::vector<Eigen::Vector3d> rvecs_eigen,
164 std::vector<Eigen::Vector3d> tvecs_eigen) {
milind-u8c72d532021-12-11 15:02:42 -0800165 HandleCharuco(rgb_image, eof, charuco_ids, charuco_corners, valid,
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800166 rvecs_eigen, tvecs_eigen);
167 }),
Jim Ostrowskicb8b4082024-01-21 02:23:46 -0800168 // TODO: Need to make this work for pi or orin
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800169 image_callback_(
170 image_event_loop_,
Jim Ostrowski3dc21642024-01-22 16:08:40 -0800171 absl::StrCat("/", aos::network::ParsePiOrOrin(hostname).value(),
172 std::to_string(
173 aos::network::ParsePiOrOrinNumber(hostname).value()),
174 image_channel),
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800175 [this](cv::Mat rgb_image, const monotonic_clock::time_point eof) {
176 charuco_extractor_.HandleImage(rgb_image, eof);
milind-u8c72d532021-12-11 15:02:42 -0800177 }),
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800178 data_(data),
179 visualizer_event_loop_(image_factory_->MakeEventLoop("visualization")),
Maxwell Hendersonecc8a7c2024-02-29 20:19:45 -0800180 visualizer_(visualizer_event_loop_.get(), image_channel) {
milind-u8c72d532021-12-11 15:02:42 -0800181 imu_factory_->OnShutdown([]() { cv::destroyAllWindows(); });
182
Jim Ostrowskiba2edd12022-12-03 15:44:37 -0800183 // Check for IMUValuesBatch topic on both /localizer and /drivetrain channels,
184 // since both are valid/possible
185 std::string imu_channel;
186 if (imu_event_loop->HasChannel<frc971::IMUValuesBatch>("/localizer")) {
187 imu_channel = "/localizer";
188 } else if (imu_event_loop->HasChannel<frc971::IMUValuesBatch>(
189 "/drivetrain")) {
190 imu_channel = "/drivetrain";
191 } else {
192 LOG(FATAL) << "Couldn't find channel with IMU data for either localizer or "
193 "drivtrain";
194 }
195
196 VLOG(2) << "Listening for " << frc971::IMUValuesBatch::GetFullyQualifiedName()
197 << " on channel: " << imu_channel;
198
milind-u8c72d532021-12-11 15:02:42 -0800199 imu_event_loop_->MakeWatcher(
Jim Ostrowskiba2edd12022-12-03 15:44:37 -0800200 imu_channel, [this](const frc971::IMUValuesBatch &imu) {
milind-u8c72d532021-12-11 15:02:42 -0800201 if (!imu.has_readings()) {
202 return;
203 }
204 for (const frc971::IMUValues *value : *imu.readings()) {
205 HandleIMU(value);
206 }
207 });
208}
209
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800210void Calibration::HandleCharuco(
211 cv::Mat rgb_image, const monotonic_clock::time_point eof,
212 std::vector<cv::Vec4i> /*charuco_ids*/,
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800213 std::vector<std::vector<cv::Point2f>> charuco_corners, bool valid,
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800214 std::vector<Eigen::Vector3d> rvecs_eigen,
215 std::vector<Eigen::Vector3d> tvecs_eigen) {
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800216 visualizer_.HandleCharuco(eof, charuco_corners);
milind-u8c72d532021-12-11 15:02:42 -0800217 if (valid) {
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800218 CHECK(rvecs_eigen.size() > 0) << "Require at least one target detected";
219 // We only use one (the first) target detected for calibration
220 data_->AddCameraPose(image_factory_->ToDistributedClock(eof),
221 rvecs_eigen[0], tvecs_eigen[0]);
milind-u8c72d532021-12-11 15:02:42 -0800222
milind-u8c72d532021-12-11 15:02:42 -0800223 Eigen::IOFormat HeavyFmt(Eigen::FullPrecision, 0, ", ", ",\n", "[", "]",
224 "[", "]");
225
226 const double age_double =
227 std::chrono::duration_cast<std::chrono::duration<double>>(
228 image_event_loop_->monotonic_now() - eof)
229 .count();
Jim Ostrowskiba2edd12022-12-03 15:44:37 -0800230 VLOG(1) << std::fixed << std::setprecision(6) << "Age: " << age_double
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800231 << ", Pose is R:" << rvecs_eigen[0].transpose().format(HeavyFmt)
232 << "\nT:" << tvecs_eigen[0].transpose().format(HeavyFmt);
milind-u8c72d532021-12-11 15:02:42 -0800233 }
234
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800235 if (FLAGS_visualize) {
236 if (FLAGS_display_undistorted) {
237 const cv::Size image_size(rgb_image.cols, rgb_image.rows);
238 cv::Mat undistorted_rgb_image(image_size, CV_8UC3);
239 cv::undistort(rgb_image, undistorted_rgb_image,
240 charuco_extractor_.camera_matrix(),
241 charuco_extractor_.dist_coeffs());
milind-u8c72d532021-12-11 15:02:42 -0800242
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800243 cv::imshow("Display undist", undistorted_rgb_image);
244 }
milind-u8c72d532021-12-11 15:02:42 -0800245
Jim Ostrowskib3cab972022-12-03 15:47:00 -0800246 cv::imshow("Display", rgb_image);
247 cv::waitKey(1);
milind-u8c72d532021-12-11 15:02:42 -0800248 }
Jim Ostrowskiba2edd12022-12-03 15:44:37 -0800249
250 if (FLAGS_save_path != "") {
251 if (!FLAGS_save_valid_only || valid) {
252 static int img_count = 0;
253 std::string image_name = absl::StrFormat("/img_%06d.png", img_count);
254 std::string path = FLAGS_save_path + image_name;
255 VLOG(2) << "Saving image to " << path;
256 cv::imwrite(path, rgb_image);
257 img_count++;
258 }
259 }
milind-u8c72d532021-12-11 15:02:42 -0800260}
261
262void Calibration::HandleIMU(const frc971::IMUValues *imu) {
Jim Ostrowskiba2edd12022-12-03 15:44:37 -0800263 // Need to check for valid values, since we sometimes don't get them
264 if (!imu->has_gyro_x() || !imu->has_gyro_y() || !imu->has_gyro_z() ||
265 !imu->has_accelerometer_x() || !imu->has_accelerometer_y() ||
266 !imu->has_accelerometer_z()) {
267 return;
268 }
269
270 VLOG(2) << "IMU " << imu;
milind-u8c72d532021-12-11 15:02:42 -0800271 imu->UnPackTo(&last_value_);
272 Eigen::Vector3d gyro(last_value_.gyro_x, last_value_.gyro_y,
273 last_value_.gyro_z);
274 Eigen::Vector3d accel(last_value_.accelerometer_x,
275 last_value_.accelerometer_y,
276 last_value_.accelerometer_z);
277
James Kuszmaul969e4ab2023-01-28 16:09:19 -0800278 // TODO: ToDistributedClock may be too noisy.
milind-u8c72d532021-12-11 15:02:42 -0800279 data_->AddImu(imu_factory_->ToDistributedClock(monotonic_clock::time_point(
280 chrono::nanoseconds(imu->monotonic_timestamp_ns()))),
Austin Schuh5b379072021-12-26 16:01:04 -0800281 gyro, accel * kG);
milind-u8c72d532021-12-11 15:02:42 -0800282}
283
Stephan Pleinesf63bde82024-01-13 15:59:33 -0800284} // namespace frc971::vision