blob: 9bbaf75e705d6d8efcec78d254844d08e8ca6ba8 [file] [log] [blame]
milind-u92195982022-01-22 20:29:31 -08001#include "y2022/vision/target_estimator.h"
2
Milind Upadhyayf61e1482022-02-11 20:42:55 -08003#include "absl/strings/str_format.h"
4#include "aos/time/time.h"
5#include "ceres/ceres.h"
6#include "frc971/control_loops/quaternion_utils.h"
Milind Upadhyayb67c6182022-10-22 13:45:45 -07007#include "frc971/vision/geometry.h"
Milind Upadhyayf61e1482022-02-11 20:42:55 -08008#include "opencv2/core/core.hpp"
9#include "opencv2/core/eigen.hpp"
10#include "opencv2/features2d.hpp"
11#include "opencv2/highgui/highgui.hpp"
12#include "opencv2/imgproc.hpp"
milind-ucafdd5d2022-03-01 19:58:57 -080013#include "y2022/constants.h"
Milind Upadhyayf61e1482022-02-11 20:42:55 -080014
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080015DEFINE_bool(freeze_roll, false, "If true, don't solve for roll");
Milind Upadhyayf61e1482022-02-11 20:42:55 -080016DEFINE_bool(freeze_pitch, false, "If true, don't solve for pitch");
17DEFINE_bool(freeze_yaw, false, "If true, don't solve for yaw");
18DEFINE_bool(freeze_camera_height, true,
19 "If true, don't solve for camera height");
20DEFINE_bool(freeze_angle_to_camera, true,
21 "If true, don't solve for polar angle to camera");
22
23DEFINE_uint64(max_num_iterations, 200,
24 "Maximum number of iterations for the ceres solver");
25DEFINE_bool(solver_output, false,
26 "If true, log the solver progress and results");
Milind Upadhyay3336f3a2022-04-01 21:45:57 -070027DEFINE_bool(draw_projected_hub, true,
28 "If true, draw the projected hub when drawing an estimate");
Milind Upadhyayf61e1482022-02-11 20:42:55 -080029
milind-u92195982022-01-22 20:29:31 -080030namespace y2022::vision {
31
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080032namespace {
33
34constexpr size_t kNumPiecesOfTape = 16;
35// Width and height of a piece of reflective tape
36constexpr double kTapePieceWidth = 0.13;
37constexpr double kTapePieceHeight = 0.05;
38// Height of the center of the tape (m)
39constexpr double kTapeCenterHeight = 2.58 + (kTapePieceHeight / 2);
40// Horizontal distance from tape to center of hub (m)
Austin Schuha685b5d2022-04-02 14:53:54 -070041constexpr double kUpperHubRadius = 1.36 / 2;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080042
43std::vector<cv::Point3d> ComputeTapePoints() {
Milind Upadhyayf61e1482022-02-11 20:42:55 -080044 std::vector<cv::Point3d> tape_points;
milind-u92195982022-01-22 20:29:31 -080045
Milind Upadhyayf61e1482022-02-11 20:42:55 -080046 constexpr size_t kNumVisiblePiecesOfTape = 5;
47 for (size_t i = 0; i < kNumVisiblePiecesOfTape; i++) {
48 // The center piece of tape is at 0 rad, so the angle indices are offset
49 // by the number of pieces of tape on each side of it
50 const double theta_index =
51 static_cast<double>(i) - ((kNumVisiblePiecesOfTape - 1) / 2);
52 // The polar angle is a multiple of the angle between tape centers
53 double theta = theta_index * ((2.0 * M_PI) / kNumPiecesOfTape);
54 tape_points.emplace_back(kUpperHubRadius * std::cos(theta),
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080055 kUpperHubRadius * std::sin(theta),
56 kTapeCenterHeight);
Milind Upadhyayf61e1482022-02-11 20:42:55 -080057 }
milind-u92195982022-01-22 20:29:31 -080058
Milind Upadhyayf61e1482022-02-11 20:42:55 -080059 return tape_points;
60}
milind-u92195982022-01-22 20:29:31 -080061
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080062std::array<cv::Point3d, 4> ComputeMiddleTapePiecePoints() {
63 std::array<cv::Point3d, 4> tape_piece_points;
64
65 // Angle that each piece of tape occupies on the hub
66 constexpr double kTapePieceAngle =
67 (kTapePieceWidth / (2.0 * M_PI * kUpperHubRadius)) * (2.0 * M_PI);
68
69 constexpr double kThetaTapeLeft = -kTapePieceAngle / 2.0;
70 constexpr double kThetaTapeRight = kTapePieceAngle / 2.0;
71
72 constexpr double kTapeTopHeight =
73 kTapeCenterHeight + (kTapePieceHeight / 2.0);
74 constexpr double kTapeBottomHeight =
75 kTapeCenterHeight - (kTapePieceHeight / 2.0);
76
77 tape_piece_points[0] = {kUpperHubRadius * std::cos(kThetaTapeLeft),
78 kUpperHubRadius * std::sin(kThetaTapeLeft),
79 kTapeTopHeight};
80 tape_piece_points[1] = {kUpperHubRadius * std::cos(kThetaTapeRight),
81 kUpperHubRadius * std::sin(kThetaTapeRight),
82 kTapeTopHeight};
83
84 tape_piece_points[2] = {kUpperHubRadius * std::cos(kThetaTapeRight),
85 kUpperHubRadius * std::sin(kThetaTapeRight),
86 kTapeBottomHeight};
87 tape_piece_points[3] = {kUpperHubRadius * std::cos(kThetaTapeLeft),
88 kUpperHubRadius * std::sin(kThetaTapeLeft),
89 kTapeBottomHeight};
90
91 return tape_piece_points;
92}
93
94} // namespace
95
Milind Upadhyayf61e1482022-02-11 20:42:55 -080096const std::vector<cv::Point3d> TargetEstimator::kTapePoints =
97 ComputeTapePoints();
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080098const std::array<cv::Point3d, 4> TargetEstimator::kMiddleTapePiecePoints =
99 ComputeMiddleTapePiecePoints();
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800100
Milind Upadhyaye5003102022-04-02 22:16:39 -0700101namespace {
102constexpr double kDefaultDistance = 3.0;
103constexpr double kDefaultYaw = M_PI;
104constexpr double kDefaultAngleToCamera = 0.0;
105} // namespace
106
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800107TargetEstimator::TargetEstimator(cv::Mat intrinsics, cv::Mat extrinsics)
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800108 : blob_stats_(),
Milind Upadhyay1c76a042022-04-02 20:42:42 -0700109 middle_blob_index_(0),
110 max_blob_area_(0.0),
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800111 image_(std::nullopt),
112 roll_(0.0),
113 pitch_(0.0),
Milind Upadhyaye5003102022-04-02 22:16:39 -0700114 yaw_(kDefaultYaw),
115 distance_(kDefaultDistance),
116 angle_to_camera_(kDefaultAngleToCamera),
milind-ucafdd5d2022-03-01 19:58:57 -0800117 // Seed camera height
118 camera_height_(extrinsics.at<double>(2, 3) +
119 constants::Values::kImuHeight()) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800120 cv::cv2eigen(intrinsics, intrinsics_);
121 cv::cv2eigen(extrinsics, extrinsics_);
122}
123
124namespace {
125void SetBoundsOrFreeze(double *param, bool freeze, double min, double max,
126 ceres::Problem *problem) {
127 if (freeze) {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800128 problem->SetParameterBlockConstant(param);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800129 } else {
130 problem->SetParameterLowerBound(param, 0, min);
131 problem->SetParameterUpperBound(param, 0, max);
132 }
133}
milind-ucafdd5d2022-03-01 19:58:57 -0800134
135// With X, Y, Z being hub axes and x, y, z being camera axes,
136// x = -Y, y = -Z, z = X
137const Eigen::Matrix3d kHubToCameraAxes =
138 (Eigen::Matrix3d() << 0.0, -1.0, 0.0, 0.0, 0.0, -1.0, 1.0, 0.0, 0.0)
139 .finished();
140
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800141} // namespace
142
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800143void TargetEstimator::Solve(
144 const std::vector<BlobDetector::BlobStats> &blob_stats,
145 std::optional<cv::Mat> image) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800146 auto start = aos::monotonic_clock::now();
147
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800148 blob_stats_ = blob_stats;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800149 image_ = image;
150
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800151 // Do nothing if no blobs were detected
152 if (blob_stats_.size() == 0) {
153 confidence_ = 0.0;
154 return;
155 }
156
157 CHECK_GE(blob_stats_.size(), 3) << "Expected at least 3 blobs";
158
Milind Upadhyayb67c6182022-10-22 13:45:45 -0700159 const auto circle = frc971::vision::Circle::Fit({blob_stats_[0].centroid,
160 blob_stats_[1].centroid,
161 blob_stats_[2].centroid});
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800162 CHECK(circle.has_value());
163
Milind Upadhyay1c76a042022-04-02 20:42:42 -0700164 max_blob_area_ = 0.0;
165
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800166 // Find the middle blob, which is the one with the angle closest to the
167 // average
168 double theta_avg = 0.0;
169 for (const auto &stats : blob_stats_) {
170 theta_avg += circle->AngleOf(stats.centroid);
Milind Upadhyay1c76a042022-04-02 20:42:42 -0700171
172 if (stats.area > max_blob_area_) {
173 max_blob_area_ = stats.area;
174 }
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800175 }
176 theta_avg /= blob_stats_.size();
177
178 double min_diff = std::numeric_limits<double>::infinity();
179 for (auto it = blob_stats_.begin(); it < blob_stats_.end(); it++) {
180 const double diff = std::abs(circle->AngleOf(it->centroid) - theta_avg);
181 if (diff < min_diff) {
182 min_diff = diff;
183 middle_blob_index_ = it - blob_stats_.begin();
184 }
185 }
186
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800187 ceres::Problem problem;
188
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800189 // x and y differences between projected centroids and blob centroids, as well
190 // as width and height differences between middle projected piece and the
191 // detected blob
192 const size_t num_residuals = (blob_stats_.size() * 2) + 2;
193
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800194 // Set up the only cost function (also known as residual). This uses
195 // auto-differentiation to obtain the derivative (jacobian).
196 ceres::CostFunction *cost_function =
197 new ceres::AutoDiffCostFunction<TargetEstimator, ceres::DYNAMIC, 1, 1, 1,
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800198 1, 1, 1>(this, num_residuals,
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800199 ceres::DO_NOT_TAKE_OWNERSHIP);
200
201 // TODO(milind): add loss function when we get more noisy data
Austin Schuha685b5d2022-04-02 14:53:54 -0700202 problem.AddResidualBlock(cost_function, new ceres::HuberLoss(2.0), &roll_,
203 &pitch_, &yaw_, &distance_, &angle_to_camera_,
204 &camera_height_);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800205
milind-ucafdd5d2022-03-01 19:58:57 -0800206 // Compute the estimated rotation of the camera using the robot rotation.
Milind Upadhyayda042bb2022-03-26 16:01:45 -0700207 const Eigen::Matrix3d extrinsics_rot =
208 Eigen::Affine3d(extrinsics_).rotation() * kHubToCameraAxes;
209 // asin returns a pitch in [-pi/2, pi/2] so this will be the correct euler
210 // angles.
211 const double pitch_seed = -std::asin(extrinsics_rot(2, 0));
212 const double roll_seed =
213 std::atan2(extrinsics_rot(2, 1) / std::cos(pitch_seed),
214 extrinsics_rot(2, 2) / std::cos(pitch_seed));
215
milind-ucafdd5d2022-03-01 19:58:57 -0800216 // TODO(milind): seed with localizer output as well
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800217
Milind Upadhyaye5003102022-04-02 22:16:39 -0700218 // If we didn't solve well last time, seed everything at the defaults so we
219 // don't get stuck in a bad state.
220 // Copied from localizer.cc
221 constexpr double kMinConfidence = 0.75;
222 if (confidence_ < kMinConfidence) {
223 roll_ = roll_seed;
224 pitch_ = pitch_seed;
225 yaw_ = kDefaultYaw;
226 distance_ = kDefaultDistance;
227 angle_to_camera_ = kDefaultAngleToCamera;
228 camera_height_ = extrinsics_(2, 3) + constants::Values::kImuHeight();
229 }
230
milind-ucafdd5d2022-03-01 19:58:57 -0800231 // Constrain the rotation to be around the localizer's, otherwise there can be
232 // multiple solutions. There shouldn't be too much roll or pitch
Milind Upadhyay1d9a9c72022-04-02 14:18:40 -0700233 if (FLAGS_freeze_roll) {
234 roll_ = roll_seed;
235 }
milind-ucafdd5d2022-03-01 19:58:57 -0800236 constexpr double kMaxRollDelta = 0.1;
237 SetBoundsOrFreeze(&roll_, FLAGS_freeze_roll, roll_seed - kMaxRollDelta,
238 roll_seed + kMaxRollDelta, &problem);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800239
Milind Upadhyay1d9a9c72022-04-02 14:18:40 -0700240 if (FLAGS_freeze_pitch) {
241 pitch_ = pitch_seed;
242 }
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800243 constexpr double kMaxPitchDelta = 0.15;
milind-ucafdd5d2022-03-01 19:58:57 -0800244 SetBoundsOrFreeze(&pitch_, FLAGS_freeze_pitch, pitch_seed - kMaxPitchDelta,
245 pitch_seed + kMaxPitchDelta, &problem);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800246 // Constrain the yaw to where the target would be visible
247 constexpr double kMaxYawDelta = M_PI / 4.0;
248 SetBoundsOrFreeze(&yaw_, FLAGS_freeze_yaw, M_PI - kMaxYawDelta,
249 M_PI + kMaxYawDelta, &problem);
250
251 constexpr double kMaxHeightDelta = 0.1;
252 SetBoundsOrFreeze(&camera_height_, FLAGS_freeze_camera_height,
253 camera_height_ - kMaxHeightDelta,
254 camera_height_ + kMaxHeightDelta, &problem);
255
256 // Distances shouldn't be too close to the target or too far
257 constexpr double kMinDistance = 1.0;
258 constexpr double kMaxDistance = 10.0;
259 SetBoundsOrFreeze(&distance_, false, kMinDistance, kMaxDistance, &problem);
260
261 // Keep the angle between +/- half of the angle between piece of tape
262 constexpr double kMaxAngle = ((2.0 * M_PI) / kNumPiecesOfTape) / 2.0;
263 SetBoundsOrFreeze(&angle_to_camera_, FLAGS_freeze_angle_to_camera, -kMaxAngle,
264 kMaxAngle, &problem);
265
266 ceres::Solver::Options options;
267 options.minimizer_progress_to_stdout = FLAGS_solver_output;
268 options.gradient_tolerance = 1e-12;
269 options.function_tolerance = 1e-16;
270 options.parameter_tolerance = 1e-12;
271 options.max_num_iterations = FLAGS_max_num_iterations;
272 ceres::Solver::Summary summary;
273 ceres::Solve(options, &problem, &summary);
274
275 auto end = aos::monotonic_clock::now();
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800276 VLOG(1) << "Target estimation elapsed time: "
277 << std::chrono::duration<double, std::milli>(end - start).count()
278 << " ms";
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800279
Milind Upadhyay1c76a042022-04-02 20:42:42 -0700280 // For computing the confidence, find the standard deviation in pixels.
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800281 std::vector<double> residual(num_residuals);
282 (*this)(&roll_, &pitch_, &yaw_, &distance_, &angle_to_camera_,
283 &camera_height_, residual.data());
284 double std_dev = 0.0;
285 for (auto it = residual.begin(); it < residual.end() - 2; it++) {
286 std_dev += std::pow(*it, 2);
Milind Upadhyay14279de2022-02-26 16:07:53 -0800287 }
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800288 std_dev /= num_residuals - 2;
289 std_dev = std::sqrt(std_dev);
290
291 // Use a sigmoid to convert the deviation into a confidence for the
292 // localizer. Fit a sigmoid to the points of (0, 1) and two other
293 // reasonable deviation-confidence combinations using
Milind Upadhyayda9a8292022-04-02 18:00:04 -0700294 // https://www.desmos.com/calculator/ha6fh9yw44
295 constexpr double kSigmoidCapacity = 1.065;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800296 // Stretch the sigmoid out correctly.
Milind Upadhyayda9a8292022-04-02 18:00:04 -0700297 // Currently, good estimates have deviations of 1 or less pixels.
298 constexpr double kSigmoidScalar = 0.06496;
299 constexpr double kSigmoidGrowthRate = -0.6221;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800300 confidence_ =
301 kSigmoidCapacity /
302 (1.0 + kSigmoidScalar * std::exp(-kSigmoidGrowthRate * std_dev));
Milind Upadhyay14279de2022-02-26 16:07:53 -0800303
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800304 if (FLAGS_solver_output) {
305 LOG(INFO) << summary.FullReport();
306
307 LOG(INFO) << "roll: " << roll_;
308 LOG(INFO) << "pitch: " << pitch_;
309 LOG(INFO) << "yaw: " << yaw_;
310 LOG(INFO) << "angle to target (based on yaw): " << angle_to_target();
311 LOG(INFO) << "angle to camera (polar): " << angle_to_camera_;
312 LOG(INFO) << "distance (polar): " << distance_;
313 LOG(INFO) << "camera height: " << camera_height_;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800314 LOG(INFO) << "standard deviation (px): " << std_dev;
Milind Upadhyay14279de2022-02-26 16:07:53 -0800315 LOG(INFO) << "confidence: " << confidence_;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800316 }
317}
318
319namespace {
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700320
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800321// Hacks to extract a double from a scalar, which is either a ceres jet or a
322// double. Only used for debugging and displaying.
323template <typename S>
324double ScalarToDouble(S s) {
325 const double *ptr = reinterpret_cast<double *>(&s);
326 return *ptr;
327}
328
329template <typename S>
330cv::Point2d ScalarPointToDouble(cv::Point_<S> p) {
331 return cv::Point2d(ScalarToDouble(p.x), ScalarToDouble(p.y));
332}
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700333
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800334} // namespace
335
336template <typename S>
337bool TargetEstimator::operator()(const S *const roll, const S *const pitch,
338 const S *const yaw, const S *const distance,
339 const S *const theta,
340 const S *const camera_height,
341 S *residual) const {
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700342 const auto H_hub_camera = ComputeHubCameraTransform(
343 *roll, *pitch, *yaw, *distance, *theta, *camera_height);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800344
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700345 // Project tape points
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800346 std::vector<cv::Point_<S>> tape_points_proj;
347 for (cv::Point3d tape_point_hub : kTapePoints) {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800348 tape_points_proj.emplace_back(ProjectToImage(tape_point_hub, H_hub_camera));
349 VLOG(2) << "Projected tape point: "
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800350 << ScalarPointToDouble(
351 tape_points_proj[tape_points_proj.size() - 1]);
352 }
353
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800354 // Find the rectangle bounding the projected piece of tape
355 std::array<cv::Point_<S>, 4> middle_tape_piece_points_proj;
356 for (auto tape_piece_it = kMiddleTapePiecePoints.begin();
357 tape_piece_it < kMiddleTapePiecePoints.end(); tape_piece_it++) {
358 middle_tape_piece_points_proj[tape_piece_it -
359 kMiddleTapePiecePoints.begin()] =
360 ProjectToImage(*tape_piece_it, H_hub_camera);
361 }
362
Austin Schuha685b5d2022-04-02 14:53:54 -0700363 // Now, find the closest tape for each blob.
364 // We don't normally see tape without matching blobs in the center. So we
365 // want to compress any gaps in the matched tape blobs. This makes it so it
366 // doesn't want to make the goal super small and skip tape blobs. The
367 // resulting accuracy is then pretty good.
368
369 // Mapping from tape index to blob index.
370 std::vector<std::pair<size_t, size_t>> tape_indices;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800371 for (size_t i = 0; i < blob_stats_.size(); i++) {
Austin Schuha685b5d2022-04-02 14:53:54 -0700372 tape_indices.emplace_back(ClosestTape(i, tape_points_proj), i);
373 VLOG(2) << "Tape indices were " << tape_indices.back().first;
374 }
375
376 std::sort(
377 tape_indices.begin(), tape_indices.end(),
378 [](const std::pair<size_t, size_t> &a,
379 const std::pair<size_t, size_t> &b) { return a.first < b.first; });
380
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700381 std::optional<size_t> middle_tape_index = std::nullopt;
Austin Schuha685b5d2022-04-02 14:53:54 -0700382 for (size_t i = 0; i < tape_indices.size(); ++i) {
383 if (tape_indices[i].second == middle_blob_index_) {
384 middle_tape_index = i;
385 }
386 }
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700387 CHECK(middle_tape_index.has_value()) << "Failed to find middle tape";
Austin Schuha685b5d2022-04-02 14:53:54 -0700388
389 if (VLOG_IS_ON(2)) {
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700390 LOG(INFO) << "Middle tape is " << *middle_tape_index << ", blob "
Austin Schuha685b5d2022-04-02 14:53:54 -0700391 << middle_blob_index_;
392 for (size_t i = 0; i < tape_indices.size(); ++i) {
393 const auto distance = DistanceFromTapeIndex(
394 tape_indices[i].second, tape_indices[i].first, tape_points_proj);
395 LOG(INFO) << "Blob index " << tape_indices[i].second << " maps to "
396 << tape_indices[i].first << " distance " << distance.x << " "
397 << distance.y;
398 }
399 }
400
401 {
402 size_t offset = 0;
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700403 for (size_t i = *middle_tape_index + 1; i < tape_indices.size(); ++i) {
Austin Schuha685b5d2022-04-02 14:53:54 -0700404 tape_indices[i].first -= offset;
405
406 if (tape_indices[i].first > tape_indices[i - 1].first + 1) {
407 offset += tape_indices[i].first - (tape_indices[i - 1].first + 1);
408 VLOG(2) << "Offset now " << offset;
409 tape_indices[i].first = tape_indices[i - 1].first + 1;
410 }
411 }
412 }
413
414 if (VLOG_IS_ON(2)) {
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700415 LOG(INFO) << "Middle tape is " << *middle_tape_index << ", blob "
Austin Schuha685b5d2022-04-02 14:53:54 -0700416 << middle_blob_index_;
417 for (size_t i = 0; i < tape_indices.size(); ++i) {
418 const auto distance = DistanceFromTapeIndex(
419 tape_indices[i].second, tape_indices[i].first, tape_points_proj);
420 LOG(INFO) << "Blob index " << tape_indices[i].second << " maps to "
421 << tape_indices[i].first << " distance " << distance.x << " "
422 << distance.y;
423 }
424 }
425
426 {
427 size_t offset = 0;
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700428 for (size_t i = *middle_tape_index; i > 0; --i) {
Austin Schuha685b5d2022-04-02 14:53:54 -0700429 tape_indices[i - 1].first -= offset;
430
431 if (tape_indices[i - 1].first + 1 < tape_indices[i].first) {
432 VLOG(2) << "Too big a gap. " << tape_indices[i].first << " and "
433 << tape_indices[i - 1].first;
434
435 offset += tape_indices[i].first - (tape_indices[i - 1].first + 1);
436 tape_indices[i - 1].first = tape_indices[i].first - 1;
437 VLOG(2) << "Offset now " << offset;
438 }
439 }
440 }
441
442 if (VLOG_IS_ON(2)) {
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700443 LOG(INFO) << "Middle tape is " << *middle_tape_index << ", blob "
Austin Schuha685b5d2022-04-02 14:53:54 -0700444 << middle_blob_index_;
445 for (size_t i = 0; i < tape_indices.size(); ++i) {
446 const auto distance = DistanceFromTapeIndex(
447 tape_indices[i].second, tape_indices[i].first, tape_points_proj);
448 LOG(INFO) << "Blob index " << tape_indices[i].second << " maps to "
449 << tape_indices[i].first << " distance " << distance.x << " "
450 << distance.y;
451 }
452 }
453
454 for (size_t i = 0; i < tape_indices.size(); ++i) {
455 const auto distance = DistanceFromTapeIndex(
456 tape_indices[i].second, tape_indices[i].first, tape_points_proj);
Milind Upadhyay1c76a042022-04-02 20:42:42 -0700457 // Scale the distance based on the blob area: larger blobs have less noise.
458 const S distance_scalar =
459 S(blob_stats_[tape_indices[i].second].area / max_blob_area_);
Austin Schuha685b5d2022-04-02 14:53:54 -0700460 VLOG(2) << "Blob index " << tape_indices[i].second << " maps to "
461 << tape_indices[i].first << " distance " << distance.x << " "
Milind Upadhyay1c76a042022-04-02 20:42:42 -0700462 << distance.y << " distance scalar "
463 << ScalarToDouble(distance_scalar);
464
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800465 // Set the residual to the (x, y) distance of the centroid from the
Austin Schuha685b5d2022-04-02 14:53:54 -0700466 // matched projected piece of tape
Milind Upadhyay1c76a042022-04-02 20:42:42 -0700467 residual[i * 2] = distance_scalar * distance.x;
468 residual[(i * 2) + 1] = distance_scalar * distance.y;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800469 }
470
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800471 // Penalize based on the difference between the size of the projected piece of
Austin Schuha685b5d2022-04-02 14:53:54 -0700472 // tape and that of the detected blobs.
473 const S middle_tape_piece_width = ceres::hypot(
474 middle_tape_piece_points_proj[2].x - middle_tape_piece_points_proj[3].x,
475 middle_tape_piece_points_proj[2].y - middle_tape_piece_points_proj[3].y);
476 const S middle_tape_piece_height = ceres::hypot(
477 middle_tape_piece_points_proj[1].x - middle_tape_piece_points_proj[2].x,
478 middle_tape_piece_points_proj[1].y - middle_tape_piece_points_proj[2].y);
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800479
Austin Schuha685b5d2022-04-02 14:53:54 -0700480 constexpr double kCenterBlobSizeScalar = 0.1;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800481 residual[blob_stats_.size() * 2] =
Austin Schuha685b5d2022-04-02 14:53:54 -0700482 kCenterBlobSizeScalar *
483 (middle_tape_piece_width -
484 static_cast<S>(blob_stats_[middle_blob_index_].size.width));
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800485 residual[(blob_stats_.size() * 2) + 1] =
Austin Schuha685b5d2022-04-02 14:53:54 -0700486 kCenterBlobSizeScalar *
487 (middle_tape_piece_height -
488 static_cast<S>(blob_stats_[middle_blob_index_].size.height));
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800489
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800490 if (image_.has_value()) {
491 // Draw the current stage of the solving
492 cv::Mat image = image_->clone();
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700493 std::vector<cv::Point2d> tape_points_proj_double;
494 for (auto point : tape_points_proj) {
495 tape_points_proj_double.emplace_back(ScalarPointToDouble(point));
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800496 }
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700497 DrawProjectedHub(tape_points_proj_double, image);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800498 cv::imshow("image", image);
499 cv::waitKey(10);
500 }
501
502 return true;
503}
504
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800505template <typename S>
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700506Eigen::Transform<S, 3, Eigen::Affine>
507TargetEstimator::ComputeHubCameraTransform(S roll, S pitch, S yaw, S distance,
508 S theta, S camera_height) const {
509 using Vector3s = Eigen::Matrix<S, 3, 1>;
510 using Affine3s = Eigen::Transform<S, 3, Eigen::Affine>;
511
512 Eigen::AngleAxis<S> roll_angle(roll, Vector3s::UnitX());
513 Eigen::AngleAxis<S> pitch_angle(pitch, Vector3s::UnitY());
514 Eigen::AngleAxis<S> yaw_angle(yaw, Vector3s::UnitZ());
515 // Construct the rotation and translation of the camera in the hub's frame
516 Eigen::Quaternion<S> R_camera_hub = yaw_angle * pitch_angle * roll_angle;
517 Vector3s T_camera_hub(distance * ceres::cos(theta),
518 distance * ceres::sin(theta), camera_height);
519
520 Affine3s H_camera_hub = Eigen::Translation<S, 3>(T_camera_hub) * R_camera_hub;
521 Affine3s H_hub_camera = H_camera_hub.inverse();
522
523 return H_hub_camera;
524}
525
526template <typename S>
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800527cv::Point_<S> TargetEstimator::ProjectToImage(
528 cv::Point3d tape_point_hub,
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700529 const Eigen::Transform<S, 3, Eigen::Affine> &H_hub_camera) const {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800530 using Vector3s = Eigen::Matrix<S, 3, 1>;
531
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800532 const Vector3s tape_point_hub_eigen =
533 Vector3s(S(tape_point_hub.x), S(tape_point_hub.y), S(tape_point_hub.z));
534 // Project the 3d tape point onto the image using the transformation and
535 // intrinsics
536 const Vector3s tape_point_proj =
milind-ucafdd5d2022-03-01 19:58:57 -0800537 intrinsics_ * (kHubToCameraAxes * (H_hub_camera * tape_point_hub_eigen));
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800538
539 // Normalize the projected point
540 return {tape_point_proj.x() / tape_point_proj.z(),
541 tape_point_proj.y() / tape_point_proj.z()};
542}
543
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800544namespace {
545template <typename S>
546cv::Point_<S> Distance(cv::Point p, cv::Point_<S> q) {
547 return cv::Point_<S>(S(p.x) - q.x, S(p.y) - q.y);
548}
549
550template <typename S>
551bool Less(cv::Point_<S> distance_1, cv::Point_<S> distance_2) {
552 return (ceres::pow(distance_1.x, 2) + ceres::pow(distance_1.y, 2) <
553 ceres::pow(distance_2.x, 2) + ceres::pow(distance_2.y, 2));
554}
555} // namespace
556
557template <typename S>
Austin Schuha685b5d2022-04-02 14:53:54 -0700558cv::Point_<S> TargetEstimator::DistanceFromTapeIndex(
559 size_t blob_index, size_t tape_index,
560 const std::vector<cv::Point_<S>> &tape_points) const {
561 return Distance(blob_stats_[blob_index].centroid, tape_points[tape_index]);
562}
563
564template <typename S>
565size_t TargetEstimator::ClosestTape(
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800566 size_t blob_index, const std::vector<cv::Point_<S>> &tape_points) const {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800567 auto distance = cv::Point_<S>(std::numeric_limits<S>::infinity(),
568 std::numeric_limits<S>::infinity());
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700569 std::optional<size_t> final_match = std::nullopt;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800570 if (blob_index == middle_blob_index_) {
571 // Fix the middle blob so the solver can't go too far off
Austin Schuha685b5d2022-04-02 14:53:54 -0700572 final_match = tape_points.size() / 2;
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700573 distance = DistanceFromTapeIndex(blob_index, *final_match, tape_points);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800574 } else {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800575 // Give the other blob_stats some freedom in case some are split into pieces
576 for (auto it = tape_points.begin(); it < tape_points.end(); it++) {
Austin Schuha685b5d2022-04-02 14:53:54 -0700577 const size_t tape_index = std::distance(tape_points.begin(), it);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800578 const auto current_distance =
Austin Schuha685b5d2022-04-02 14:53:54 -0700579 DistanceFromTapeIndex(blob_index, tape_index, tape_points);
580 if ((tape_index != (tape_points.size() / 2)) &&
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800581 Less(current_distance, distance)) {
Austin Schuha685b5d2022-04-02 14:53:54 -0700582 final_match = tape_index;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800583 distance = current_distance;
584 }
585 }
586 }
587
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700588 CHECK(final_match.has_value());
589 VLOG(2) << "Matched index " << blob_index << " to " << *final_match
Austin Schuha685b5d2022-04-02 14:53:54 -0700590 << " distance " << distance.x << " " << distance.y;
Austin Schuha685b5d2022-04-02 14:53:54 -0700591
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700592 return *final_match;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800593}
594
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700595void TargetEstimator::DrawProjectedHub(
596 const std::vector<cv::Point2d> &tape_points_proj,
597 cv::Mat view_image) const {
598 for (size_t i = 0; i < tape_points_proj.size() - 1; i++) {
599 cv::line(view_image, ScalarPointToDouble(tape_points_proj[i]),
600 ScalarPointToDouble(tape_points_proj[i + 1]),
601 cv::Scalar(255, 255, 255));
602 cv::circle(view_image, ScalarPointToDouble(tape_points_proj[i]), 2,
603 cv::Scalar(255, 20, 147), cv::FILLED);
604 cv::circle(view_image, ScalarPointToDouble(tape_points_proj[i + 1]), 2,
605 cv::Scalar(255, 20, 147), cv::FILLED);
606 }
607}
608
609void TargetEstimator::DrawEstimate(cv::Mat view_image) const {
610 if (FLAGS_draw_projected_hub) {
611 // Draw projected hub
612 const auto H_hub_camera = ComputeHubCameraTransform(
613 roll_, pitch_, yaw_, distance_, angle_to_camera_, camera_height_);
614 std::vector<cv::Point2d> tape_points_proj;
615 for (cv::Point3d tape_point_hub : kTapePoints) {
616 tape_points_proj.emplace_back(
617 ProjectToImage(tape_point_hub, H_hub_camera));
618 }
619 DrawProjectedHub(tape_points_proj, view_image);
620 }
621
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800622 constexpr int kTextX = 10;
Milind Upadhyay2da80bb2022-03-12 22:54:35 -0800623 int text_y = 0;
624 constexpr int kTextSpacing = 25;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800625
626 const auto kTextColor = cv::Scalar(0, 255, 255);
Milind Upadhyay2da80bb2022-03-12 22:54:35 -0800627 constexpr double kFontScale = 0.6;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800628
Jim Ostrowskib3d5f582022-04-02 20:22:49 -0700629 cv::putText(view_image,
630 absl::StrFormat("Distance: %.3f m (%.3f in)", distance_,
631 distance_ / 0.0254),
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800632 cv::Point(kTextX, text_y += kTextSpacing),
633 cv::FONT_HERSHEY_DUPLEX, kFontScale, kTextColor, 2);
634 cv::putText(view_image,
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700635 absl::StrFormat("Angle to target: %.3f", angle_to_target()),
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800636 cv::Point(kTextX, text_y += kTextSpacing),
637 cv::FONT_HERSHEY_DUPLEX, kFontScale, kTextColor, 2);
638 cv::putText(view_image,
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700639 absl::StrFormat("Angle to camera: %.3f", angle_to_camera_),
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800640 cv::Point(kTextX, text_y += kTextSpacing),
641 cv::FONT_HERSHEY_DUPLEX, kFontScale, kTextColor, 2);
642
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700643 cv::putText(view_image,
644 absl::StrFormat("Roll: %.3f, pitch: %.3f, yaw: %.3f", roll_,
645 pitch_, yaw_),
Milind Upadhyay14279de2022-02-26 16:07:53 -0800646 cv::Point(kTextX, text_y += kTextSpacing),
647 cv::FONT_HERSHEY_DUPLEX, kFontScale, kTextColor, 2);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800648
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700649 cv::putText(view_image, absl::StrFormat("Confidence: %.3f", confidence_),
650 cv::Point(kTextX, text_y += kTextSpacing),
651 cv::FONT_HERSHEY_DUPLEX, kFontScale, kTextColor, 2);
milind-u92195982022-01-22 20:29:31 -0800652}
653
654} // namespace y2022::vision