blob: 873cf43b449bde23893bdfe0d965d7ee06856219 [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"
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080010#include "opencv2/highgui/highgui.hpp"
milind-u92195982022-01-22 20:29:31 -080011#include "opencv2/imgproc.hpp"
milind-udb98afa2022-03-01 19:54:57 -080012#include "y2022/vision/geometry.h"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080013
Yash Chainani6acad6f2022-02-03 10:52:53 -080014DEFINE_uint64(red_delta, 100,
15 "Required difference between green pixels vs. red");
Milind Upadhyayae998722022-03-13 12:45:55 -070016DEFINE_uint64(blue_delta, 1,
Yash Chainani6acad6f2022-02-03 10:52:53 -080017 "Required difference between green pixels vs. blue");
18
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080019DEFINE_bool(use_outdoors, false,
20 "If true, change thresholds to handle outdoor illumination");
Yash Chainani6acad6f2022-02-03 10:52:53 -080021DEFINE_uint64(outdoors_red_delta, 100,
22 "Difference between green pixels vs. red, when outdoors");
Milind Upadhyayf61e1482022-02-11 20:42:55 -080023DEFINE_uint64(outdoors_blue_delta, 1,
Yash Chainani6acad6f2022-02-03 10:52:53 -080024 "Difference between green pixels vs. blue, when outdoors");
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080025
26namespace y2022 {
27namespace vision {
28
Milind Upadhyayec41e132022-02-05 17:14:05 -080029cv::Mat BlobDetector::ThresholdImage(cv::Mat bgr_image) {
Yash Chainani6acad6f2022-02-03 10:52:53 -080030 size_t red_delta = FLAGS_red_delta;
31 size_t blue_delta = FLAGS_blue_delta;
32
33 if (FLAGS_use_outdoors) {
34 red_delta = FLAGS_outdoors_red_delta;
Milind Upadhyayf61e1482022-02-11 20:42:55 -080035 blue_delta = FLAGS_outdoors_blue_delta;
Yash Chainani6acad6f2022-02-03 10:52:53 -080036 }
37
Milind Upadhyayec41e132022-02-05 17:14:05 -080038 cv::Mat binarized_image(cv::Size(bgr_image.cols, bgr_image.rows), CV_8UC1);
39 for (int row = 0; row < bgr_image.rows; row++) {
40 for (int col = 0; col < bgr_image.cols; col++) {
41 cv::Vec3b pixel = bgr_image.at<cv::Vec3b>(row, col);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080042 uint8_t blue = pixel.val[0];
43 uint8_t green = pixel.val[1];
44 uint8_t red = pixel.val[2];
45 // Simple filter that looks for green pixels sufficiently brigher than
46 // red and blue
Yash Chainani6acad6f2022-02-03 10:52:53 -080047 if ((green > blue + blue_delta) && (green > red + red_delta)) {
milind-u61f21e82022-01-23 18:34:11 -080048 binarized_image.at<uint8_t>(row, col) = 255;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080049 } else {
milind-u61f21e82022-01-23 18:34:11 -080050 binarized_image.at<uint8_t>(row, col) = 0;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080051 }
52 }
53 }
54
Milind Upadhyayae998722022-03-13 12:45:55 -070055 // Fill in the contours on the binarized image so that we don't detect
56 // multiple blobs in one
57 const auto blobs = FindBlobs(binarized_image);
58 for (auto it = blobs.begin(); it < blobs.end(); it++) {
59 cv::drawContours(binarized_image, blobs, it - blobs.begin(),
60 cv::Scalar(255), cv::FILLED);
61 }
62
milind-u61f21e82022-01-23 18:34:11 -080063 return binarized_image;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080064}
65
66std::vector<std::vector<cv::Point>> BlobDetector::FindBlobs(
67 cv::Mat binarized_image) {
68 // find the contours (blob outlines)
69 std::vector<std::vector<cv::Point>> contours;
70 std::vector<cv::Vec4i> hierarchy;
71 cv::findContours(binarized_image, contours, hierarchy, cv::RETR_CCOMP,
72 cv::CHAIN_APPROX_SIMPLE);
73
74 return contours;
75}
76
milind-u61f21e82022-01-23 18:34:11 -080077std::vector<BlobDetector::BlobStats> BlobDetector::ComputeStats(
Milind Upadhyayf61e1482022-02-11 20:42:55 -080078 const std::vector<std::vector<cv::Point>> &blobs) {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080079 cv::Mat img = cv::Mat::zeros(640, 480, CV_8UC3);
80
milind-u61f21e82022-01-23 18:34:11 -080081 std::vector<BlobDetector::BlobStats> blob_stats;
82 for (auto blob : blobs) {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080083 // Opencv doesn't have height and width ordered correctly.
84 // The rotated size will only be used after blobs have been filtered, so it
85 // is ok to assume that width is the larger side
86 const cv::Size rotated_rect_size_unordered = cv::minAreaRect(blob).size;
87 const cv::Size rotated_rect_size = {
88 std::max(rotated_rect_size_unordered.width,
89 rotated_rect_size_unordered.height),
90 std::min(rotated_rect_size_unordered.width,
91 rotated_rect_size_unordered.height)};
92 const cv::Size bounding_box_size = cv::boundingRect(blob).size();
93
Milind Upadhyayf61e1482022-02-11 20:42:55 -080094 cv::Moments moments = cv::moments(blob);
milind-u61f21e82022-01-23 18:34:11 -080095
96 const auto centroid =
97 cv::Point(moments.m10 / moments.m00, moments.m01 / moments.m00);
98 const double aspect_ratio =
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080099 static_cast<double>(bounding_box_size.width) / bounding_box_size.height;
milind-u61f21e82022-01-23 18:34:11 -0800100 const double area = moments.m00;
Henry Speisere45e7a22022-02-04 23:17:01 -0800101 const size_t num_points = blob.size();
milind-u61f21e82022-01-23 18:34:11 -0800102
Henry Speisere45e7a22022-02-04 23:17:01 -0800103 blob_stats.emplace_back(
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800104 BlobStats{centroid, rotated_rect_size, aspect_ratio, area, num_points});
milind-u61f21e82022-01-23 18:34:11 -0800105 }
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800106
milind-u61f21e82022-01-23 18:34:11 -0800107 return blob_stats;
108}
109
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800110void BlobDetector::FilterBlobs(BlobResult *blob_result) {
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800111 std::vector<std::vector<cv::Point>> filtered_blobs;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800112 std::vector<BlobStats> filtered_stats;
milind-u92195982022-01-22 20:29:31 -0800113
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800114 auto blob_it = blob_result->unfiltered_blobs.begin();
115 auto stats_it = blob_result->blob_stats.begin();
116 while (blob_it < blob_result->unfiltered_blobs.end() &&
117 stats_it < blob_result->blob_stats.end()) {
milind-u61f21e82022-01-23 18:34:11 -0800118 constexpr double kTapeAspectRatio = 5.0 / 2.0;
Milind Upadhyayec41e132022-02-05 17:14:05 -0800119 constexpr double kAspectRatioThreshold = 1.6;
milind-u61f21e82022-01-23 18:34:11 -0800120 constexpr double kMinArea = 10;
Milind Upadhyayec41e132022-02-05 17:14:05 -0800121 constexpr size_t kMinNumPoints = 6;
milind-u92195982022-01-22 20:29:31 -0800122
milind-u61f21e82022-01-23 18:34:11 -0800123 // Remove all blobs that are at the bottom of the image, have a different
Milind Upadhyayec41e132022-02-05 17:14:05 -0800124 // aspect ratio than the tape, or have too little area or points.
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800125 if ((std::abs(1.0 - kTapeAspectRatio / stats_it->aspect_ratio) <
milind-u61f21e82022-01-23 18:34:11 -0800126 kAspectRatioThreshold) &&
Milind Upadhyayec41e132022-02-05 17:14:05 -0800127 (stats_it->area >= kMinArea) &&
128 (stats_it->num_points >= kMinNumPoints)) {
milind-u61f21e82022-01-23 18:34:11 -0800129 filtered_blobs.push_back(*blob_it);
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800130 filtered_stats.push_back(*stats_it);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800131 }
milind-u61f21e82022-01-23 18:34:11 -0800132 blob_it++;
133 stats_it++;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800134 }
milind-u92195982022-01-22 20:29:31 -0800135
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800136 // Threshold for mean distance from a blob centroid to a circle.
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800137 constexpr double kCircleDistanceThreshold = 10.0;
Milind Upadhyayec41e132022-02-05 17:14:05 -0800138 // We should only expect to see blobs between these angles on a circle.
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800139 constexpr double kDegToRad = M_PI / 180.0;
140 constexpr double kMinBlobAngle = 50.0 * kDegToRad;
Milind Upadhyayec41e132022-02-05 17:14:05 -0800141 constexpr double kMaxBlobAngle = M_PI - kMinBlobAngle;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800142 std::vector<std::vector<cv::Point>> blob_circle;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800143 std::vector<BlobStats> blob_circle_stats;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800144 Circle circle;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800145
146 // If we see more than this number of blobs after filtering based on
147 // color/size, the circle fit may detect noise so just return no blobs.
Milind Upadhyay2b4404c2022-02-04 21:20:57 -0800148 constexpr size_t kMinFilteredBlobs = 3;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800149 constexpr size_t kMaxFilteredBlobs = 50;
Milind Upadhyay2b4404c2022-02-04 21:20:57 -0800150 if (filtered_blobs.size() >= kMinFilteredBlobs &&
151 filtered_blobs.size() <= kMaxFilteredBlobs) {
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800152 constexpr size_t kRansacIterations = 15;
153 for (size_t i = 0; i < kRansacIterations; i++) {
154 // Pick 3 random blobs and see how many fit on their circle
155 const size_t j = std::rand() % filtered_blobs.size();
156 const size_t k = std::rand() % filtered_blobs.size();
157 const size_t l = std::rand() % filtered_blobs.size();
158
159 // Restart if the random indices clash
160 if ((j == k) || (j == l) || (k == l)) {
161 i--;
162 continue;
163 }
164
165 std::vector<std::vector<cv::Point>> current_blobs{
166 filtered_blobs[j], filtered_blobs[k], filtered_blobs[l]};
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800167 std::vector<BlobStats> current_stats{filtered_stats[j], filtered_stats[k],
168 filtered_stats[l]};
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800169 const std::optional<Circle> current_circle =
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800170 Circle::Fit({current_stats[0].centroid, current_stats[1].centroid,
171 current_stats[2].centroid});
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800172
173 // Make sure that a circle could be created from the points
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800174 if (!current_circle) {
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800175 continue;
176 }
177
Milind Upadhyayec41e132022-02-05 17:14:05 -0800178 // Only try to fit points to this circle if all of these are between
179 // certain angles.
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800180 if (current_circle->InAngleRange(current_stats[0].centroid, kMinBlobAngle,
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800181 kMaxBlobAngle) &&
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800182 current_circle->InAngleRange(current_stats[1].centroid, kMinBlobAngle,
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800183 kMaxBlobAngle) &&
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800184 current_circle->InAngleRange(current_stats[2].centroid, kMinBlobAngle,
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800185 kMaxBlobAngle)) {
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800186 for (size_t m = 0; m < filtered_blobs.size(); m++) {
187 // Add this blob to the list if it is close to the circle, is on the
188 // top half, and isn't one of the other blobs
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800189 if ((m != j) && (m != k) && (m != l) &&
190 current_circle->InAngleRange(filtered_stats[m].centroid,
191 kMinBlobAngle, kMaxBlobAngle) &&
192 (current_circle->DistanceTo(filtered_stats[m].centroid) <
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800193 kCircleDistanceThreshold)) {
194 current_blobs.emplace_back(filtered_blobs[m]);
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800195 current_stats.emplace_back(filtered_stats[m]);
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800196 }
197 }
198
199 if (current_blobs.size() > blob_circle.size()) {
200 blob_circle = current_blobs;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800201 blob_circle_stats = current_stats;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800202 circle = *current_circle;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800203 }
204 }
205 }
206 }
207
208 cv::Point avg_centroid(-1, -1);
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800209 if (blob_circle.size() > 0) {
210 for (const auto &stats : blob_circle_stats) {
211 avg_centroid.x += stats.centroid.x;
212 avg_centroid.y += stats.centroid.y;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800213 }
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800214 avg_centroid.x /= blob_circle_stats.size();
215 avg_centroid.y /= blob_circle_stats.size();
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800216 }
217
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800218 blob_result->filtered_blobs = blob_circle;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800219 blob_result->filtered_stats = blob_circle_stats;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800220 blob_result->centroid = avg_centroid;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800221}
222
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800223void BlobDetector::DrawBlobs(const BlobResult &blob_result,
224 cv::Mat view_image) {
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800225 CHECK_GT(view_image.cols, 0);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800226 if (blob_result.unfiltered_blobs.size() > 0) {
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800227 // Draw blobs unfilled, with red color border
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800228 cv::drawContours(view_image, blob_result.unfiltered_blobs, -1,
229 cv::Scalar(0, 0, 255), 0);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800230 }
231
James Kuszmauld230d7a2022-03-06 15:00:43 -0800232 if (blob_result.filtered_blobs.size() > 0) {
233 cv::drawContours(view_image, blob_result.filtered_blobs, -1,
234 cv::Scalar(0, 100, 0), cv::FILLED);
235 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800236
Milind Upadhyay2da80bb2022-03-12 22:54:35 -0800237 for (const auto &blob : blob_result.filtered_blobs) {
238 cv::polylines(view_image, blob, true, cv::Scalar(0, 255, 0));
239 }
240
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800241 static constexpr double kCircleRadius = 2.0;
milind-u92195982022-01-22 20:29:31 -0800242 // Draw blob centroids
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800243 for (auto stats : blob_result.blob_stats) {
244 cv::circle(view_image, stats.centroid, kCircleRadius,
245 cv::Scalar(0, 215, 255), cv::FILLED);
246 }
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800247 for (auto stats : blob_result.filtered_stats) {
248 cv::circle(view_image, stats.centroid, kCircleRadius, cv::Scalar(0, 255, 0),
milind-u61f21e82022-01-23 18:34:11 -0800249 cv::FILLED);
250 }
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800251
252 // Draw average centroid
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800253 cv::circle(view_image, blob_result.centroid, kCircleRadius,
254 cv::Scalar(255, 255, 0), cv::FILLED);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800255}
256
Milind Upadhyayec41e132022-02-05 17:14:05 -0800257void BlobDetector::ExtractBlobs(cv::Mat bgr_image,
Milind Upadhyay25610d22022-02-07 15:35:26 -0800258 BlobDetector::BlobResult *blob_result) {
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800259 auto start = aos::monotonic_clock::now();
Milind Upadhyayec41e132022-02-05 17:14:05 -0800260 blob_result->binarized_image = ThresholdImage(bgr_image);
Milind Upadhyay25610d22022-02-07 15:35:26 -0800261 blob_result->unfiltered_blobs = FindBlobs(blob_result->binarized_image);
262 blob_result->blob_stats = ComputeStats(blob_result->unfiltered_blobs);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800263 FilterBlobs(blob_result);
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800264 auto end = aos::monotonic_clock::now();
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800265 VLOG(1) << "Blob detection elapsed time: "
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800266 << std::chrono::duration<double, std::milli>(end - start).count()
267 << " ms";
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800268}
269
270} // namespace vision
271} // namespace y2022