blob: 8ac96cd4b5bccc07dacc9299bd818ed9cb71b0f9 [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
20cv::Mat BlobDetector::ThresholdImage(cv::Mat rgb_image) {
milind-u61f21e82022-01-23 18:34:11 -080021 cv::Mat binarized_image(cv::Size(rgb_image.cols, rgb_image.rows), CV_8UC1);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080022 for (int row = 0; row < rgb_image.rows; row++) {
23 for (int col = 0; col < rgb_image.cols; col++) {
24 cv::Vec3b pixel = rgb_image.at<cv::Vec3b>(row, col);
25 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;
68 const size_t points = blob.size();
69
70 blob_stats.emplace_back(BlobStats{centroid, aspect_ratio, area, points});
71 }
72 return blob_stats;
73}
74
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -080075namespace {
76
77// Linear equation in the form ax + by = c
78struct Line {
79 public:
80 double a, b, c;
81
82 std::optional<cv::Point2d> Intersection(const Line &l) const {
83 // Use Cramer's rule to solve for the intersection
84 const double denominator = Determinant(a, b, l.a, l.b);
85 const double numerator_x = Determinant(c, b, l.c, l.b);
86 const double numerator_y = Determinant(a, c, l.a, l.c);
87
88 std::optional<cv::Point2d> intersection = std::nullopt;
89 // Return nullopt if the denominator is 0, meaning the same slopes
90 if (denominator != 0) {
91 intersection =
92 cv::Point2d(numerator_x / denominator, numerator_y / denominator);
93 }
94
95 return intersection;
96 }
97
98 private: // Determinant of [[a, b], [c, d]]
99 static double Determinant(double a, double b, double c, double d) {
100 return (a * d) - (b * c);
101 }
102};
103
104struct Circle {
105 public:
106 cv::Point2d center;
107 double radius;
108
109 static std::optional<Circle> Fit(std::vector<cv::Point2d> centroids) {
110 CHECK_EQ(centroids.size(), 3ul);
111 // For the 3 points, we have 3 equations in the form
112 // (x - h)^2 + (y - k)^2 = r^2
113 // Manipulate them to solve for the center and radius
114 // (x1 - h)^2 + (y1 - k)^2 = r^2 ->
115 // x1^2 + h^2 - 2x1h + y1^2 + k^2 - 2y1k = r^2
116 // Also, (x2 - h)^2 + (y2 - k)^2 = r^2
117 // Subtracting these two, we get
118 // x1^2 - x2^2 - 2h(x1 - x2) + y1^2 - y2^2 - 2k(y1 - y2) = 0 ->
119 // h(x1 - x2) + k(y1 - y2) = (-x1^2 + x2^2 - y1^2 + y2^2) / -2
120 // Doing the same with equations 1 and 3, we get the second linear equation
121 // h(x1 - x3) + k(y1 - y3) = (-x1^2 + x3^2 - y1^2 + y3^2) / -2
122 // Now, we can solve for their intersection and find the center
123 const auto l =
124 Line{centroids[0].x - centroids[1].x, centroids[0].y - centroids[1].y,
125 (-std::pow(centroids[0].x, 2) + std::pow(centroids[1].x, 2) -
126 std::pow(centroids[0].y, 2) + std::pow(centroids[1].y, 2)) /
127 -2.0};
128 const auto m =
129 Line{centroids[0].x - centroids[2].x, centroids[0].y - centroids[2].y,
130 (-std::pow(centroids[0].x, 2) + std::pow(centroids[2].x, 2) -
131 std::pow(centroids[0].y, 2) + std::pow(centroids[2].y, 2)) /
132 -2.0};
133 const auto center = l.Intersection(m);
134
135 std::optional<Circle> circle = std::nullopt;
136 if (center) {
137 // Now find the radius
138 const double radius = cv::norm(centroids[0] - *center);
139 circle = Circle{*center, radius};
140 }
141 return circle;
142 }
143
144 double DistanceTo(cv::Point2d p) const {
145 // Translate the point so that the circle orgin can be (0, 0)
146 const auto p_prime = cv::Point2d(p.y - center.y, p.x - center.x);
147 // 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
152 // Inverted because y-coordinates go backwards
153 bool OnTopHalf(cv::Point2d p) const { return p.y <= center.y; }
154};
155
156} // namespace
157
158std::pair<std::vector<std::vector<cv::Point>>, cv::Point>
159BlobDetector::FilterBlobs(std::vector<std::vector<cv::Point>> blobs,
160 std::vector<BlobDetector::BlobStats> blob_stats) {
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800161 std::vector<std::vector<cv::Point>> filtered_blobs;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800162 std::vector<BlobStats> filtered_stats;
milind-u92195982022-01-22 20:29:31 -0800163
milind-u61f21e82022-01-23 18:34:11 -0800164 auto blob_it = blobs.begin();
165 auto stats_it = blob_stats.begin();
166 while (blob_it < blobs.end() && stats_it < blob_stats.end()) {
milind-u92195982022-01-22 20:29:31 -0800167 // To estimate the maximum y, we can figure out the y value of the blobs
168 // when the camera is the farthest from the target, at the field corner.
169 // We can solve for the pitch of the blob:
170 // blob_pitch = atan((height_tape - height_camera) / depth) + camera_pitch
171 // The triangle with the height of the tape above the camera and the camera
172 // depth is similar to the one with the focal length in y pixels and the y
173 // coordinate offset from the center of the image.
174 // Therefore y_offset = focal_length_y * tan(blob_pitch), and
175 // y = -(y_offset - offset_y)
milind-u61f21e82022-01-23 18:34:11 -0800176 constexpr int kMaxY = 400;
177 constexpr double kTapeAspectRatio = 5.0 / 2.0;
178 constexpr double kAspectRatioThreshold = 1.5;
179 constexpr double kMinArea = 10;
milind-u92195982022-01-22 20:29:31 -0800180 constexpr size_t kMinPoints = 6;
181
milind-u61f21e82022-01-23 18:34:11 -0800182 // Remove all blobs that are at the bottom of the image, have a different
183 // aspect ratio than the tape, or have too little area or points
milind-u92195982022-01-22 20:29:31 -0800184 // TODO(milind): modify to take into account that blobs will be on the side.
milind-u61f21e82022-01-23 18:34:11 -0800185 if ((stats_it->centroid.y <= kMaxY) &&
186 (std::abs(kTapeAspectRatio - stats_it->aspect_ratio) <
187 kAspectRatioThreshold) &&
188 (stats_it->area >= kMinArea) && (stats_it->points >= kMinPoints)) {
189 filtered_blobs.push_back(*blob_it);
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800190 filtered_stats.push_back(*stats_it);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800191 }
milind-u61f21e82022-01-23 18:34:11 -0800192 blob_it++;
193 stats_it++;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800194 }
milind-u92195982022-01-22 20:29:31 -0800195
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800196 // Threshold for mean distance from a blob centroid to a circle.
197 constexpr double kCircleDistanceThreshold = 5.0;
198 std::vector<std::vector<cv::Point>> blob_circle;
199 std::vector<cv::Point2d> centroids;
200
201 // If we see more than this number of blobs after filtering based on
202 // color/size, the circle fit may detect noise so just return no blobs.
Milind Upadhyay2b4404c2022-02-04 21:20:57 -0800203 constexpr size_t kMinFilteredBlobs = 3;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800204 constexpr size_t kMaxFilteredBlobs = 50;
Milind Upadhyay2b4404c2022-02-04 21:20:57 -0800205 if (filtered_blobs.size() >= kMinFilteredBlobs &&
206 filtered_blobs.size() <= kMaxFilteredBlobs) {
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800207 constexpr size_t kRansacIterations = 15;
208 for (size_t i = 0; i < kRansacIterations; i++) {
209 // Pick 3 random blobs and see how many fit on their circle
210 const size_t j = std::rand() % filtered_blobs.size();
211 const size_t k = std::rand() % filtered_blobs.size();
212 const size_t l = std::rand() % filtered_blobs.size();
213
214 // Restart if the random indices clash
215 if ((j == k) || (j == l) || (k == l)) {
216 i--;
217 continue;
218 }
219
220 std::vector<std::vector<cv::Point>> current_blobs{
221 filtered_blobs[j], filtered_blobs[k], filtered_blobs[l]};
222 std::vector<cv::Point2d> current_centroids{filtered_stats[j].centroid,
223 filtered_stats[k].centroid,
224 filtered_stats[l].centroid};
225 const std::optional<Circle> circle = Circle::Fit(current_centroids);
226
227 // Make sure that a circle could be created from the points
228 if (!circle) {
229 continue;
230 }
231
232 // Only try to fit points to this circle if all of these are on the top
233 // half, like how the blobs should be
234 if (circle->OnTopHalf(current_centroids[0]) &&
235 circle->OnTopHalf(current_centroids[1]) &&
236 circle->OnTopHalf(current_centroids[2])) {
237 for (size_t m = 0; m < filtered_blobs.size(); m++) {
238 // Add this blob to the list if it is close to the circle, is on the
239 // top half, and isn't one of the other blobs
240 if ((m != i) && (m != j) && (m != k) &&
241 circle->OnTopHalf(filtered_stats[m].centroid) &&
242 (circle->DistanceTo(filtered_stats[m].centroid) <
243 kCircleDistanceThreshold)) {
244 current_blobs.emplace_back(filtered_blobs[m]);
245 current_centroids.emplace_back(filtered_stats[m].centroid);
246 }
247 }
248
249 if (current_blobs.size() > blob_circle.size()) {
250 blob_circle = current_blobs;
251 centroids = current_centroids;
252 }
253 }
254 }
255 }
256
257 cv::Point avg_centroid(-1, -1);
258 if (centroids.size() > 0) {
259 for (auto centroid : centroids) {
260 avg_centroid.x += centroid.x;
261 avg_centroid.y += centroid.y;
262 }
263 avg_centroid.x /= centroids.size();
264 avg_centroid.y /= centroids.size();
265 }
266
267 return {blob_circle, avg_centroid};
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800268}
269
270void BlobDetector::DrawBlobs(
milind-u61f21e82022-01-23 18:34:11 -0800271 cv::Mat view_image,
272 const std::vector<std::vector<cv::Point>> &unfiltered_blobs,
273 const std::vector<std::vector<cv::Point>> &filtered_blobs,
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800274 const std::vector<BlobStats> &blob_stats, cv::Point centroid) {
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800275 CHECK_GT(view_image.cols, 0);
276 if (unfiltered_blobs.size() > 0) {
277 // Draw blobs unfilled, with red color border
milind-u92195982022-01-22 20:29:31 -0800278 cv::drawContours(view_image, unfiltered_blobs, -1, cv::Scalar(0, 0, 255),
279 0);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800280 }
281
milind-u92195982022-01-22 20:29:31 -0800282 cv::drawContours(view_image, filtered_blobs, -1, cv::Scalar(0, 255, 0),
283 cv::FILLED);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800284
milind-u92195982022-01-22 20:29:31 -0800285 // Draw blob centroids
milind-u61f21e82022-01-23 18:34:11 -0800286 for (auto stats : blob_stats) {
287 cv::circle(view_image, stats.centroid, 2, cv::Scalar(255, 0, 0),
288 cv::FILLED);
289 }
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800290
291 // Draw average centroid
292 cv::circle(view_image, centroid, 3, cv::Scalar(255, 255, 0), cv::FILLED);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800293}
294
295void BlobDetector::ExtractBlobs(
Milind Upadhyay2b4404c2022-02-04 21:20:57 -0800296 cv::Mat rgb_image, cv::Mat &binarized_image, cv::Mat blob_image,
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800297 std::vector<std::vector<cv::Point>> &filtered_blobs,
298 std::vector<std::vector<cv::Point>> &unfiltered_blobs,
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800299 std::vector<BlobStats> &blob_stats, cv::Point &centroid) {
300 auto start = aos::monotonic_clock::now();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800301 binarized_image = ThresholdImage(rgb_image);
302 unfiltered_blobs = FindBlobs(binarized_image);
milind-u61f21e82022-01-23 18:34:11 -0800303 blob_stats = ComputeStats(unfiltered_blobs);
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800304 auto filtered_pair = FilterBlobs(unfiltered_blobs, blob_stats);
305 filtered_blobs = filtered_pair.first;
306 centroid = filtered_pair.second;
307 auto end = aos::monotonic_clock::now();
308 LOG(INFO) << "Blob detection elapsed time: "
309 << std::chrono::duration<double, std::milli>(end - start).count()
310 << " ms";
311 DrawBlobs(blob_image, unfiltered_blobs, filtered_blobs, blob_stats, centroid);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800312}
313
314} // namespace vision
315} // namespace y2022