blob: 76b16ca9c64d2e0dae3cca73a3d37604f501e37b [file] [log] [blame]
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -08001#include "y2022/vision/blob_detector.h"
2
milind-u92195982022-01-22 20:29:31 -08003#include <cmath>
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -08004#include <optional>
milind-u92195982022-01-22 20:29:31 -08005#include <string>
6
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -08007#include "aos/network/team_number.h"
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -08008#include "aos/time/time.h"
milind-u92195982022-01-22 20:29:31 -08009#include "opencv2/features2d.hpp"
10#include "opencv2/imgproc.hpp"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080011
12DEFINE_uint64(green_delta, 50,
13 "Required difference between green pixels vs. red and blue");
14DEFINE_bool(use_outdoors, false,
15 "If true, change thresholds to handle outdoor illumination");
16
17namespace y2022 {
18namespace vision {
19
Milind Upadhyayec41e132022-02-05 17:14:05 -080020cv::Mat BlobDetector::ThresholdImage(cv::Mat bgr_image) {
21 cv::Mat binarized_image(cv::Size(bgr_image.cols, bgr_image.rows), CV_8UC1);
22 for (int row = 0; row < bgr_image.rows; row++) {
23 for (int col = 0; col < bgr_image.cols; col++) {
24 cv::Vec3b pixel = bgr_image.at<cv::Vec3b>(row, col);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080025 uint8_t blue = pixel.val[0];
26 uint8_t green = pixel.val[1];
27 uint8_t red = pixel.val[2];
28 // Simple filter that looks for green pixels sufficiently brigher than
29 // red and blue
milind-u92195982022-01-22 20:29:31 -080030 if ((green > blue + FLAGS_green_delta) &&
31 (green > red + FLAGS_green_delta)) {
milind-u61f21e82022-01-23 18:34:11 -080032 binarized_image.at<uint8_t>(row, col) = 255;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080033 } else {
milind-u61f21e82022-01-23 18:34:11 -080034 binarized_image.at<uint8_t>(row, col) = 0;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080035 }
36 }
37 }
38
milind-u61f21e82022-01-23 18:34:11 -080039 return binarized_image;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080040}
41
42std::vector<std::vector<cv::Point>> BlobDetector::FindBlobs(
43 cv::Mat binarized_image) {
44 // find the contours (blob outlines)
45 std::vector<std::vector<cv::Point>> contours;
46 std::vector<cv::Vec4i> hierarchy;
47 cv::findContours(binarized_image, contours, hierarchy, cv::RETR_CCOMP,
48 cv::CHAIN_APPROX_SIMPLE);
49
50 return contours;
51}
52
milind-u61f21e82022-01-23 18:34:11 -080053std::vector<BlobDetector::BlobStats> BlobDetector::ComputeStats(
54 std::vector<std::vector<cv::Point>> blobs) {
55 std::vector<BlobDetector::BlobStats> blob_stats;
56 for (auto blob : blobs) {
57 // Make the blob convex before finding bounding box
58 std::vector<cv::Point> convex_blob;
59 cv::convexHull(blob, convex_blob);
60 auto blob_size = cv::boundingRect(convex_blob).size();
61 cv::Moments moments = cv::moments(convex_blob);
62
63 const auto centroid =
64 cv::Point(moments.m10 / moments.m00, moments.m01 / moments.m00);
65 const double aspect_ratio =
66 static_cast<double>(blob_size.width) / blob_size.height;
67 const double area = moments.m00;
Henry Speisere45e7a22022-02-04 23:17:01 -080068 const size_t num_points = blob.size();
milind-u61f21e82022-01-23 18:34:11 -080069
Henry Speisere45e7a22022-02-04 23:17:01 -080070 blob_stats.emplace_back(
71 BlobStats{centroid, aspect_ratio, area, num_points});
milind-u61f21e82022-01-23 18:34:11 -080072 }
73 return blob_stats;
74}
75
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -080076namespace {
77
78// Linear equation in the form ax + by = c
79struct Line {
80 public:
81 double a, b, c;
82
83 std::optional<cv::Point2d> Intersection(const Line &l) const {
84 // Use Cramer's rule to solve for the intersection
85 const double denominator = Determinant(a, b, l.a, l.b);
86 const double numerator_x = Determinant(c, b, l.c, l.b);
87 const double numerator_y = Determinant(a, c, l.a, l.c);
88
89 std::optional<cv::Point2d> intersection = std::nullopt;
90 // Return nullopt if the denominator is 0, meaning the same slopes
91 if (denominator != 0) {
92 intersection =
93 cv::Point2d(numerator_x / denominator, numerator_y / denominator);
94 }
95
96 return intersection;
97 }
98
99 private: // Determinant of [[a, b], [c, d]]
100 static double Determinant(double a, double b, double c, double d) {
101 return (a * d) - (b * c);
102 }
103};
104
105struct Circle {
106 public:
107 cv::Point2d center;
108 double radius;
109
110 static std::optional<Circle> Fit(std::vector<cv::Point2d> centroids) {
111 CHECK_EQ(centroids.size(), 3ul);
112 // For the 3 points, we have 3 equations in the form
113 // (x - h)^2 + (y - k)^2 = r^2
114 // Manipulate them to solve for the center and radius
115 // (x1 - h)^2 + (y1 - k)^2 = r^2 ->
116 // x1^2 + h^2 - 2x1h + y1^2 + k^2 - 2y1k = r^2
117 // Also, (x2 - h)^2 + (y2 - k)^2 = r^2
118 // Subtracting these two, we get
119 // x1^2 - x2^2 - 2h(x1 - x2) + y1^2 - y2^2 - 2k(y1 - y2) = 0 ->
120 // h(x1 - x2) + k(y1 - y2) = (-x1^2 + x2^2 - y1^2 + y2^2) / -2
121 // Doing the same with equations 1 and 3, we get the second linear equation
122 // h(x1 - x3) + k(y1 - y3) = (-x1^2 + x3^2 - y1^2 + y3^2) / -2
123 // Now, we can solve for their intersection and find the center
124 const auto l =
125 Line{centroids[0].x - centroids[1].x, centroids[0].y - centroids[1].y,
126 (-std::pow(centroids[0].x, 2) + std::pow(centroids[1].x, 2) -
127 std::pow(centroids[0].y, 2) + std::pow(centroids[1].y, 2)) /
128 -2.0};
129 const auto m =
130 Line{centroids[0].x - centroids[2].x, centroids[0].y - centroids[2].y,
131 (-std::pow(centroids[0].x, 2) + std::pow(centroids[2].x, 2) -
132 std::pow(centroids[0].y, 2) + std::pow(centroids[2].y, 2)) /
133 -2.0};
134 const auto center = l.Intersection(m);
135
136 std::optional<Circle> circle = std::nullopt;
137 if (center) {
138 // Now find the radius
139 const double radius = cv::norm(centroids[0] - *center);
140 circle = Circle{*center, radius};
141 }
142 return circle;
143 }
144
145 double DistanceTo(cv::Point2d p) const {
Milind Upadhyayec41e132022-02-05 17:14:05 -0800146 const auto p_prime = TranslateToOrigin(p);
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800147 // Now, the distance is simply the difference between distance from the
148 // origin to p' and the radius.
149 return std::abs(cv::norm(p_prime) - radius);
150 }
151
Milind Upadhyayec41e132022-02-05 17:14:05 -0800152 bool InAngleRange(cv::Point2d p, double theta_min, double theta_max) const {
153 auto p_prime = TranslateToOrigin(p);
154 // Flip the y because y values go downwards.
155 p_prime.y *= -1;
156 const double theta = std::atan2(p_prime.y, p_prime.x);
157 return (theta >= theta_min && theta <= theta_max);
158 }
159
160 private:
161 // Translate the point on the circle
162 // as if the circle's center is the origin (0,0)
163 cv::Point2d TranslateToOrigin(cv::Point2d p) const {
164 return cv::Point2d(p.x - center.x, p.y - center.y);
165 }
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800166};
167
168} // namespace
169
170std::pair<std::vector<std::vector<cv::Point>>, cv::Point>
171BlobDetector::FilterBlobs(std::vector<std::vector<cv::Point>> blobs,
172 std::vector<BlobDetector::BlobStats> blob_stats) {
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800173 std::vector<std::vector<cv::Point>> filtered_blobs;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800174 std::vector<BlobStats> filtered_stats;
milind-u92195982022-01-22 20:29:31 -0800175
milind-u61f21e82022-01-23 18:34:11 -0800176 auto blob_it = blobs.begin();
177 auto stats_it = blob_stats.begin();
178 while (blob_it < blobs.end() && stats_it < blob_stats.end()) {
milind-u92195982022-01-22 20:29:31 -0800179 // To estimate the maximum y, we can figure out the y value of the blobs
180 // when the camera is the farthest from the target, at the field corner.
181 // We can solve for the pitch of the blob:
182 // blob_pitch = atan((height_tape - height_camera) / depth) + camera_pitch
183 // The triangle with the height of the tape above the camera and the camera
184 // depth is similar to the one with the focal length in y pixels and the y
185 // coordinate offset from the center of the image.
186 // Therefore y_offset = focal_length_y * tan(blob_pitch), and
187 // y = -(y_offset - offset_y)
milind-u61f21e82022-01-23 18:34:11 -0800188 constexpr int kMaxY = 400;
189 constexpr double kTapeAspectRatio = 5.0 / 2.0;
Milind Upadhyayec41e132022-02-05 17:14:05 -0800190 constexpr double kAspectRatioThreshold = 1.6;
milind-u61f21e82022-01-23 18:34:11 -0800191 constexpr double kMinArea = 10;
Milind Upadhyayec41e132022-02-05 17:14:05 -0800192 constexpr size_t kMinNumPoints = 6;
milind-u92195982022-01-22 20:29:31 -0800193
milind-u61f21e82022-01-23 18:34:11 -0800194 // Remove all blobs that are at the bottom of the image, have a different
Milind Upadhyayec41e132022-02-05 17:14:05 -0800195 // aspect ratio than the tape, or have too little area or points.
milind-u61f21e82022-01-23 18:34:11 -0800196 if ((stats_it->centroid.y <= kMaxY) &&
197 (std::abs(kTapeAspectRatio - stats_it->aspect_ratio) <
198 kAspectRatioThreshold) &&
Milind Upadhyayec41e132022-02-05 17:14:05 -0800199 (stats_it->area >= kMinArea) &&
200 (stats_it->num_points >= kMinNumPoints)) {
milind-u61f21e82022-01-23 18:34:11 -0800201 filtered_blobs.push_back(*blob_it);
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800202 filtered_stats.push_back(*stats_it);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800203 }
milind-u61f21e82022-01-23 18:34:11 -0800204 blob_it++;
205 stats_it++;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800206 }
milind-u92195982022-01-22 20:29:31 -0800207
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800208 // Threshold for mean distance from a blob centroid to a circle.
209 constexpr double kCircleDistanceThreshold = 5.0;
Milind Upadhyayec41e132022-02-05 17:14:05 -0800210 // We should only expect to see blobs between these angles on a circle.
211 constexpr double kMinBlobAngle = M_PI / 3;
212 constexpr double kMaxBlobAngle = M_PI - kMinBlobAngle;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800213 std::vector<std::vector<cv::Point>> blob_circle;
214 std::vector<cv::Point2d> centroids;
215
216 // If we see more than this number of blobs after filtering based on
217 // color/size, the circle fit may detect noise so just return no blobs.
Milind Upadhyay2b4404c2022-02-04 21:20:57 -0800218 constexpr size_t kMinFilteredBlobs = 3;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800219 constexpr size_t kMaxFilteredBlobs = 50;
Milind Upadhyay2b4404c2022-02-04 21:20:57 -0800220 if (filtered_blobs.size() >= kMinFilteredBlobs &&
221 filtered_blobs.size() <= kMaxFilteredBlobs) {
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800222 constexpr size_t kRansacIterations = 15;
223 for (size_t i = 0; i < kRansacIterations; i++) {
224 // Pick 3 random blobs and see how many fit on their circle
225 const size_t j = std::rand() % filtered_blobs.size();
226 const size_t k = std::rand() % filtered_blobs.size();
227 const size_t l = std::rand() % filtered_blobs.size();
228
229 // Restart if the random indices clash
230 if ((j == k) || (j == l) || (k == l)) {
231 i--;
232 continue;
233 }
234
235 std::vector<std::vector<cv::Point>> current_blobs{
236 filtered_blobs[j], filtered_blobs[k], filtered_blobs[l]};
237 std::vector<cv::Point2d> current_centroids{filtered_stats[j].centroid,
238 filtered_stats[k].centroid,
239 filtered_stats[l].centroid};
240 const std::optional<Circle> circle = Circle::Fit(current_centroids);
241
242 // Make sure that a circle could be created from the points
243 if (!circle) {
244 continue;
245 }
246
Milind Upadhyayec41e132022-02-05 17:14:05 -0800247 // Only try to fit points to this circle if all of these are between
248 // certain angles.
249 if (circle->InAngleRange(current_centroids[0], kMinBlobAngle,
250 kMaxBlobAngle) &&
251 circle->InAngleRange(current_centroids[1], kMinBlobAngle,
252 kMaxBlobAngle) &&
253 circle->InAngleRange(current_centroids[2], kMinBlobAngle,
254 kMaxBlobAngle)) {
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800255 for (size_t m = 0; m < filtered_blobs.size(); m++) {
256 // Add this blob to the list if it is close to the circle, is on the
257 // top half, and isn't one of the other blobs
258 if ((m != i) && (m != j) && (m != k) &&
Milind Upadhyayec41e132022-02-05 17:14:05 -0800259 circle->InAngleRange(filtered_stats[m].centroid, kMinBlobAngle,
260 kMaxBlobAngle) &&
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800261 (circle->DistanceTo(filtered_stats[m].centroid) <
262 kCircleDistanceThreshold)) {
263 current_blobs.emplace_back(filtered_blobs[m]);
264 current_centroids.emplace_back(filtered_stats[m].centroid);
265 }
266 }
267
268 if (current_blobs.size() > blob_circle.size()) {
269 blob_circle = current_blobs;
270 centroids = current_centroids;
271 }
272 }
273 }
274 }
275
276 cv::Point avg_centroid(-1, -1);
277 if (centroids.size() > 0) {
278 for (auto centroid : centroids) {
279 avg_centroid.x += centroid.x;
280 avg_centroid.y += centroid.y;
281 }
282 avg_centroid.x /= centroids.size();
283 avg_centroid.y /= centroids.size();
284 }
285
286 return {blob_circle, avg_centroid};
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800287}
288
289void BlobDetector::DrawBlobs(
milind-u61f21e82022-01-23 18:34:11 -0800290 cv::Mat view_image,
291 const std::vector<std::vector<cv::Point>> &unfiltered_blobs,
292 const std::vector<std::vector<cv::Point>> &filtered_blobs,
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800293 const std::vector<BlobStats> &blob_stats, cv::Point centroid) {
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800294 CHECK_GT(view_image.cols, 0);
295 if (unfiltered_blobs.size() > 0) {
296 // Draw blobs unfilled, with red color border
milind-u92195982022-01-22 20:29:31 -0800297 cv::drawContours(view_image, unfiltered_blobs, -1, cv::Scalar(0, 0, 255),
298 0);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800299 }
300
milind-u92195982022-01-22 20:29:31 -0800301 cv::drawContours(view_image, filtered_blobs, -1, cv::Scalar(0, 255, 0),
302 cv::FILLED);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800303
milind-u92195982022-01-22 20:29:31 -0800304 // Draw blob centroids
milind-u61f21e82022-01-23 18:34:11 -0800305 for (auto stats : blob_stats) {
306 cv::circle(view_image, stats.centroid, 2, cv::Scalar(255, 0, 0),
307 cv::FILLED);
308 }
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800309
310 // Draw average centroid
311 cv::circle(view_image, centroid, 3, cv::Scalar(255, 255, 0), cv::FILLED);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800312}
313
Milind Upadhyayec41e132022-02-05 17:14:05 -0800314void BlobDetector::ExtractBlobs(cv::Mat bgr_image,
Milind Upadhyay25610d22022-02-07 15:35:26 -0800315 BlobDetector::BlobResult *blob_result) {
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800316 auto start = aos::monotonic_clock::now();
Milind Upadhyayec41e132022-02-05 17:14:05 -0800317 blob_result->binarized_image = ThresholdImage(bgr_image);
Milind Upadhyay25610d22022-02-07 15:35:26 -0800318 blob_result->unfiltered_blobs = FindBlobs(blob_result->binarized_image);
319 blob_result->blob_stats = ComputeStats(blob_result->unfiltered_blobs);
320 auto filtered_pair =
321 FilterBlobs(blob_result->unfiltered_blobs, blob_result->blob_stats);
322 blob_result->filtered_blobs = filtered_pair.first;
323 blob_result->centroid = filtered_pair.second;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800324 auto end = aos::monotonic_clock::now();
325 LOG(INFO) << "Blob detection elapsed time: "
326 << std::chrono::duration<double, std::milli>(end - start).count()
327 << " ms";
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800328}
329
330} // namespace vision
331} // namespace y2022