blob: 14f9342efb4f1415964248242766cef94b1bc3b0 [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 Upadhyay8f38ad82022-03-03 10:06:18 -08007#include "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)
41constexpr double kUpperHubRadius = 1.22 / 2;
42
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
101TargetEstimator::TargetEstimator(cv::Mat intrinsics, cv::Mat extrinsics)
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800102 : blob_stats_(),
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800103 image_(std::nullopt),
104 roll_(0.0),
105 pitch_(0.0),
106 yaw_(M_PI),
107 distance_(3.0),
108 angle_to_camera_(0.0),
milind-ucafdd5d2022-03-01 19:58:57 -0800109 // Seed camera height
110 camera_height_(extrinsics.at<double>(2, 3) +
111 constants::Values::kImuHeight()) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800112 cv::cv2eigen(intrinsics, intrinsics_);
113 cv::cv2eigen(extrinsics, extrinsics_);
114}
115
116namespace {
117void SetBoundsOrFreeze(double *param, bool freeze, double min, double max,
118 ceres::Problem *problem) {
119 if (freeze) {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800120 problem->SetParameterBlockConstant(param);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800121 } else {
122 problem->SetParameterLowerBound(param, 0, min);
123 problem->SetParameterUpperBound(param, 0, max);
124 }
125}
milind-ucafdd5d2022-03-01 19:58:57 -0800126
127// With X, Y, Z being hub axes and x, y, z being camera axes,
128// x = -Y, y = -Z, z = X
129const Eigen::Matrix3d kHubToCameraAxes =
130 (Eigen::Matrix3d() << 0.0, -1.0, 0.0, 0.0, 0.0, -1.0, 1.0, 0.0, 0.0)
131 .finished();
132
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800133} // namespace
134
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800135void TargetEstimator::Solve(
136 const std::vector<BlobDetector::BlobStats> &blob_stats,
137 std::optional<cv::Mat> image) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800138 auto start = aos::monotonic_clock::now();
139
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800140 blob_stats_ = blob_stats;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800141 image_ = image;
142
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800143 // Do nothing if no blobs were detected
144 if (blob_stats_.size() == 0) {
145 confidence_ = 0.0;
146 return;
147 }
148
149 CHECK_GE(blob_stats_.size(), 3) << "Expected at least 3 blobs";
150
151 const auto circle =
152 Circle::Fit({blob_stats_[0].centroid, blob_stats_[1].centroid,
153 blob_stats_[2].centroid});
154 CHECK(circle.has_value());
155
156 // Find the middle blob, which is the one with the angle closest to the
157 // average
158 double theta_avg = 0.0;
159 for (const auto &stats : blob_stats_) {
160 theta_avg += circle->AngleOf(stats.centroid);
161 }
162 theta_avg /= blob_stats_.size();
163
164 double min_diff = std::numeric_limits<double>::infinity();
165 for (auto it = blob_stats_.begin(); it < blob_stats_.end(); it++) {
166 const double diff = std::abs(circle->AngleOf(it->centroid) - theta_avg);
167 if (diff < min_diff) {
168 min_diff = diff;
169 middle_blob_index_ = it - blob_stats_.begin();
170 }
171 }
172
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800173 ceres::Problem problem;
174
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800175 // x and y differences between projected centroids and blob centroids, as well
176 // as width and height differences between middle projected piece and the
177 // detected blob
178 const size_t num_residuals = (blob_stats_.size() * 2) + 2;
179
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800180 // Set up the only cost function (also known as residual). This uses
181 // auto-differentiation to obtain the derivative (jacobian).
182 ceres::CostFunction *cost_function =
183 new ceres::AutoDiffCostFunction<TargetEstimator, ceres::DYNAMIC, 1, 1, 1,
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800184 1, 1, 1>(this, num_residuals,
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800185 ceres::DO_NOT_TAKE_OWNERSHIP);
186
187 // TODO(milind): add loss function when we get more noisy data
188 problem.AddResidualBlock(cost_function, nullptr, &roll_, &pitch_, &yaw_,
189 &distance_, &angle_to_camera_, &camera_height_);
190
milind-ucafdd5d2022-03-01 19:58:57 -0800191 // Compute the estimated rotation of the camera using the robot rotation.
Milind Upadhyayda042bb2022-03-26 16:01:45 -0700192 const Eigen::Matrix3d extrinsics_rot =
193 Eigen::Affine3d(extrinsics_).rotation() * kHubToCameraAxes;
194 // asin returns a pitch in [-pi/2, pi/2] so this will be the correct euler
195 // angles.
196 const double pitch_seed = -std::asin(extrinsics_rot(2, 0));
197 const double roll_seed =
198 std::atan2(extrinsics_rot(2, 1) / std::cos(pitch_seed),
199 extrinsics_rot(2, 2) / std::cos(pitch_seed));
200
milind-ucafdd5d2022-03-01 19:58:57 -0800201 // TODO(milind): seed with localizer output as well
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800202
milind-ucafdd5d2022-03-01 19:58:57 -0800203 // Constrain the rotation to be around the localizer's, otherwise there can be
204 // multiple solutions. There shouldn't be too much roll or pitch
205 constexpr double kMaxRollDelta = 0.1;
206 SetBoundsOrFreeze(&roll_, FLAGS_freeze_roll, roll_seed - kMaxRollDelta,
207 roll_seed + kMaxRollDelta, &problem);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800208
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800209 constexpr double kMaxPitchDelta = 0.15;
milind-ucafdd5d2022-03-01 19:58:57 -0800210 SetBoundsOrFreeze(&pitch_, FLAGS_freeze_pitch, pitch_seed - kMaxPitchDelta,
211 pitch_seed + kMaxPitchDelta, &problem);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800212 // Constrain the yaw to where the target would be visible
213 constexpr double kMaxYawDelta = M_PI / 4.0;
214 SetBoundsOrFreeze(&yaw_, FLAGS_freeze_yaw, M_PI - kMaxYawDelta,
215 M_PI + kMaxYawDelta, &problem);
216
217 constexpr double kMaxHeightDelta = 0.1;
218 SetBoundsOrFreeze(&camera_height_, FLAGS_freeze_camera_height,
219 camera_height_ - kMaxHeightDelta,
220 camera_height_ + kMaxHeightDelta, &problem);
221
222 // Distances shouldn't be too close to the target or too far
223 constexpr double kMinDistance = 1.0;
224 constexpr double kMaxDistance = 10.0;
225 SetBoundsOrFreeze(&distance_, false, kMinDistance, kMaxDistance, &problem);
226
227 // Keep the angle between +/- half of the angle between piece of tape
228 constexpr double kMaxAngle = ((2.0 * M_PI) / kNumPiecesOfTape) / 2.0;
229 SetBoundsOrFreeze(&angle_to_camera_, FLAGS_freeze_angle_to_camera, -kMaxAngle,
230 kMaxAngle, &problem);
231
232 ceres::Solver::Options options;
233 options.minimizer_progress_to_stdout = FLAGS_solver_output;
234 options.gradient_tolerance = 1e-12;
235 options.function_tolerance = 1e-16;
236 options.parameter_tolerance = 1e-12;
237 options.max_num_iterations = FLAGS_max_num_iterations;
238 ceres::Solver::Summary summary;
239 ceres::Solve(options, &problem, &summary);
240
241 auto end = aos::monotonic_clock::now();
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800242 VLOG(1) << "Target estimation elapsed time: "
243 << std::chrono::duration<double, std::milli>(end - start).count()
244 << " ms";
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800245
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800246 // For computing the confidence, find the standard deviation in pixels
247 std::vector<double> residual(num_residuals);
248 (*this)(&roll_, &pitch_, &yaw_, &distance_, &angle_to_camera_,
249 &camera_height_, residual.data());
250 double std_dev = 0.0;
251 for (auto it = residual.begin(); it < residual.end() - 2; it++) {
252 std_dev += std::pow(*it, 2);
Milind Upadhyay14279de2022-02-26 16:07:53 -0800253 }
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800254 std_dev /= num_residuals - 2;
255 std_dev = std::sqrt(std_dev);
256
257 // Use a sigmoid to convert the deviation into a confidence for the
258 // localizer. Fit a sigmoid to the points of (0, 1) and two other
259 // reasonable deviation-confidence combinations using
260 // https://www.desmos.com/calculator/try0pgx1qw
261 constexpr double kSigmoidCapacity = 1.045;
262 // Stretch the sigmoid out correctly.
263 // Currently, good estimates have deviations of around 2 pixels.
264 constexpr double kSigmoidScalar = 0.04452;
265 constexpr double kSigmoidGrowthRate = -0.4021;
266 confidence_ =
267 kSigmoidCapacity /
268 (1.0 + kSigmoidScalar * std::exp(-kSigmoidGrowthRate * std_dev));
Milind Upadhyay14279de2022-02-26 16:07:53 -0800269
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800270 if (FLAGS_solver_output) {
271 LOG(INFO) << summary.FullReport();
272
273 LOG(INFO) << "roll: " << roll_;
274 LOG(INFO) << "pitch: " << pitch_;
275 LOG(INFO) << "yaw: " << yaw_;
276 LOG(INFO) << "angle to target (based on yaw): " << angle_to_target();
277 LOG(INFO) << "angle to camera (polar): " << angle_to_camera_;
278 LOG(INFO) << "distance (polar): " << distance_;
279 LOG(INFO) << "camera height: " << camera_height_;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800280 LOG(INFO) << "standard deviation (px): " << std_dev;
Milind Upadhyay14279de2022-02-26 16:07:53 -0800281 LOG(INFO) << "confidence: " << confidence_;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800282 }
283}
284
285namespace {
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700286
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800287// Hacks to extract a double from a scalar, which is either a ceres jet or a
288// double. Only used for debugging and displaying.
289template <typename S>
290double ScalarToDouble(S s) {
291 const double *ptr = reinterpret_cast<double *>(&s);
292 return *ptr;
293}
294
295template <typename S>
296cv::Point2d ScalarPointToDouble(cv::Point_<S> p) {
297 return cv::Point2d(ScalarToDouble(p.x), ScalarToDouble(p.y));
298}
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700299
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800300} // namespace
301
302template <typename S>
303bool TargetEstimator::operator()(const S *const roll, const S *const pitch,
304 const S *const yaw, const S *const distance,
305 const S *const theta,
306 const S *const camera_height,
307 S *residual) const {
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700308 const auto H_hub_camera = ComputeHubCameraTransform(
309 *roll, *pitch, *yaw, *distance, *theta, *camera_height);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800310
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700311 // Project tape points
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800312 std::vector<cv::Point_<S>> tape_points_proj;
313 for (cv::Point3d tape_point_hub : kTapePoints) {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800314 tape_points_proj.emplace_back(ProjectToImage(tape_point_hub, H_hub_camera));
315 VLOG(2) << "Projected tape point: "
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800316 << ScalarPointToDouble(
317 tape_points_proj[tape_points_proj.size() - 1]);
318 }
319
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800320 // Find the rectangle bounding the projected piece of tape
321 std::array<cv::Point_<S>, 4> middle_tape_piece_points_proj;
322 for (auto tape_piece_it = kMiddleTapePiecePoints.begin();
323 tape_piece_it < kMiddleTapePiecePoints.end(); tape_piece_it++) {
324 middle_tape_piece_points_proj[tape_piece_it -
325 kMiddleTapePiecePoints.begin()] =
326 ProjectToImage(*tape_piece_it, H_hub_camera);
327 }
328
329 for (size_t i = 0; i < blob_stats_.size(); i++) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800330 const auto distance = DistanceFromTape(i, tape_points_proj);
331 // Set the residual to the (x, y) distance of the centroid from the
332 // nearest projected piece of tape
333 residual[i * 2] = distance.x;
334 residual[(i * 2) + 1] = distance.y;
335 }
336
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800337 // Penalize based on the difference between the size of the projected piece of
338 // tape and that of the detected blobs. Use the squared size to avoid taking a
339 // norm, which ceres can't handle well
340 const S middle_tape_piece_width_squared =
341 ceres::pow(middle_tape_piece_points_proj[2].x -
342 middle_tape_piece_points_proj[3].x,
343 2) +
344 ceres::pow(middle_tape_piece_points_proj[2].y -
345 middle_tape_piece_points_proj[3].y,
346 2);
347 const S middle_tape_piece_height_squared =
348 ceres::pow(middle_tape_piece_points_proj[1].x -
349 middle_tape_piece_points_proj[2].x,
350 2) +
351 ceres::pow(middle_tape_piece_points_proj[1].y -
352 middle_tape_piece_points_proj[2].y,
353 2);
354
355 residual[blob_stats_.size() * 2] =
356 middle_tape_piece_width_squared -
357 std::pow(blob_stats_[middle_blob_index_].size.width, 2);
358 residual[(blob_stats_.size() * 2) + 1] =
359 middle_tape_piece_height_squared -
360 std::pow(blob_stats_[middle_blob_index_].size.height, 2);
361
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800362 if (image_.has_value()) {
363 // Draw the current stage of the solving
364 cv::Mat image = image_->clone();
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700365 std::vector<cv::Point2d> tape_points_proj_double;
366 for (auto point : tape_points_proj) {
367 tape_points_proj_double.emplace_back(ScalarPointToDouble(point));
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800368 }
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700369 DrawProjectedHub(tape_points_proj_double, image);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800370 cv::imshow("image", image);
371 cv::waitKey(10);
372 }
373
374 return true;
375}
376
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800377template <typename S>
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700378Eigen::Transform<S, 3, Eigen::Affine>
379TargetEstimator::ComputeHubCameraTransform(S roll, S pitch, S yaw, S distance,
380 S theta, S camera_height) const {
381 using Vector3s = Eigen::Matrix<S, 3, 1>;
382 using Affine3s = Eigen::Transform<S, 3, Eigen::Affine>;
383
384 Eigen::AngleAxis<S> roll_angle(roll, Vector3s::UnitX());
385 Eigen::AngleAxis<S> pitch_angle(pitch, Vector3s::UnitY());
386 Eigen::AngleAxis<S> yaw_angle(yaw, Vector3s::UnitZ());
387 // Construct the rotation and translation of the camera in the hub's frame
388 Eigen::Quaternion<S> R_camera_hub = yaw_angle * pitch_angle * roll_angle;
389 Vector3s T_camera_hub(distance * ceres::cos(theta),
390 distance * ceres::sin(theta), camera_height);
391
392 Affine3s H_camera_hub = Eigen::Translation<S, 3>(T_camera_hub) * R_camera_hub;
393 Affine3s H_hub_camera = H_camera_hub.inverse();
394
395 return H_hub_camera;
396}
397
398template <typename S>
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800399cv::Point_<S> TargetEstimator::ProjectToImage(
400 cv::Point3d tape_point_hub,
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700401 const Eigen::Transform<S, 3, Eigen::Affine> &H_hub_camera) const {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800402 using Vector3s = Eigen::Matrix<S, 3, 1>;
403
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800404 const Vector3s tape_point_hub_eigen =
405 Vector3s(S(tape_point_hub.x), S(tape_point_hub.y), S(tape_point_hub.z));
406 // Project the 3d tape point onto the image using the transformation and
407 // intrinsics
408 const Vector3s tape_point_proj =
milind-ucafdd5d2022-03-01 19:58:57 -0800409 intrinsics_ * (kHubToCameraAxes * (H_hub_camera * tape_point_hub_eigen));
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800410
411 // Normalize the projected point
412 return {tape_point_proj.x() / tape_point_proj.z(),
413 tape_point_proj.y() / tape_point_proj.z()};
414}
415
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800416namespace {
417template <typename S>
418cv::Point_<S> Distance(cv::Point p, cv::Point_<S> q) {
419 return cv::Point_<S>(S(p.x) - q.x, S(p.y) - q.y);
420}
421
422template <typename S>
423bool Less(cv::Point_<S> distance_1, cv::Point_<S> distance_2) {
424 return (ceres::pow(distance_1.x, 2) + ceres::pow(distance_1.y, 2) <
425 ceres::pow(distance_2.x, 2) + ceres::pow(distance_2.y, 2));
426}
427} // namespace
428
429template <typename S>
430cv::Point_<S> TargetEstimator::DistanceFromTape(
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800431 size_t blob_index, const std::vector<cv::Point_<S>> &tape_points) const {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800432 auto distance = cv::Point_<S>(std::numeric_limits<S>::infinity(),
433 std::numeric_limits<S>::infinity());
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800434 if (blob_index == middle_blob_index_) {
435 // Fix the middle blob so the solver can't go too far off
436 distance = Distance(blob_stats_[middle_blob_index_].centroid,
437 tape_points[tape_points.size() / 2]);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800438 } else {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800439 // Give the other blob_stats some freedom in case some are split into pieces
440 for (auto it = tape_points.begin(); it < tape_points.end(); it++) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800441 const auto current_distance =
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800442 Distance(blob_stats_[blob_index].centroid, *it);
443 if ((it != tape_points.begin() + (tape_points.size() / 2)) &&
444 Less(current_distance, distance)) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800445 distance = current_distance;
446 }
447 }
448 }
449
450 return distance;
451}
452
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700453void TargetEstimator::DrawProjectedHub(
454 const std::vector<cv::Point2d> &tape_points_proj,
455 cv::Mat view_image) const {
456 for (size_t i = 0; i < tape_points_proj.size() - 1; i++) {
457 cv::line(view_image, ScalarPointToDouble(tape_points_proj[i]),
458 ScalarPointToDouble(tape_points_proj[i + 1]),
459 cv::Scalar(255, 255, 255));
460 cv::circle(view_image, ScalarPointToDouble(tape_points_proj[i]), 2,
461 cv::Scalar(255, 20, 147), cv::FILLED);
462 cv::circle(view_image, ScalarPointToDouble(tape_points_proj[i + 1]), 2,
463 cv::Scalar(255, 20, 147), cv::FILLED);
464 }
465}
466
467void TargetEstimator::DrawEstimate(cv::Mat view_image) const {
468 if (FLAGS_draw_projected_hub) {
469 // Draw projected hub
470 const auto H_hub_camera = ComputeHubCameraTransform(
471 roll_, pitch_, yaw_, distance_, angle_to_camera_, camera_height_);
472 std::vector<cv::Point2d> tape_points_proj;
473 for (cv::Point3d tape_point_hub : kTapePoints) {
474 tape_points_proj.emplace_back(
475 ProjectToImage(tape_point_hub, H_hub_camera));
476 }
477 DrawProjectedHub(tape_points_proj, view_image);
478 }
479
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800480 constexpr int kTextX = 10;
Milind Upadhyay2da80bb2022-03-12 22:54:35 -0800481 int text_y = 0;
482 constexpr int kTextSpacing = 25;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800483
484 const auto kTextColor = cv::Scalar(0, 255, 255);
Milind Upadhyay2da80bb2022-03-12 22:54:35 -0800485 constexpr double kFontScale = 0.6;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800486
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700487 cv::putText(view_image, absl::StrFormat("Distance: %.3f", distance_),
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800488 cv::Point(kTextX, text_y += kTextSpacing),
489 cv::FONT_HERSHEY_DUPLEX, kFontScale, kTextColor, 2);
490 cv::putText(view_image,
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700491 absl::StrFormat("Angle to target: %.3f", angle_to_target()),
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800492 cv::Point(kTextX, text_y += kTextSpacing),
493 cv::FONT_HERSHEY_DUPLEX, kFontScale, kTextColor, 2);
494 cv::putText(view_image,
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700495 absl::StrFormat("Angle to camera: %.3f", angle_to_camera_),
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800496 cv::Point(kTextX, text_y += kTextSpacing),
497 cv::FONT_HERSHEY_DUPLEX, kFontScale, kTextColor, 2);
498
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700499 cv::putText(view_image,
500 absl::StrFormat("Roll: %.3f, pitch: %.3f, yaw: %.3f", roll_,
501 pitch_, yaw_),
Milind Upadhyay14279de2022-02-26 16:07:53 -0800502 cv::Point(kTextX, text_y += kTextSpacing),
503 cv::FONT_HERSHEY_DUPLEX, kFontScale, kTextColor, 2);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800504
Milind Upadhyay3336f3a2022-04-01 21:45:57 -0700505 cv::putText(view_image, absl::StrFormat("Confidence: %.3f", confidence_),
506 cv::Point(kTextX, text_y += kTextSpacing),
507 cv::FONT_HERSHEY_DUPLEX, kFontScale, kTextColor, 2);
milind-u92195982022-01-22 20:29:31 -0800508}
509
510} // namespace y2022::vision