blob: 70ff1b2064fead510eb9efc1751d67052124e711 [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
milind-u92195982022-01-22 20:29:31 -08007#include "opencv2/features2d.hpp"
Milind Upadhyay8f38ad82022-03-03 10:06:18 -08008#include "opencv2/highgui/highgui.hpp"
milind-u92195982022-01-22 20:29:31 -08009#include "opencv2/imgproc.hpp"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080010
Philipp Schrader790cb542023-07-05 21:06:52 -070011#include "aos/network/team_number.h"
12#include "aos/time/time.h"
13#include "frc971/vision/geometry.h"
14
Milind Upadhyayf67f67d2022-03-27 14:29:47 -070015DEFINE_bool(
Milind Upadhyay1d9a9c72022-04-02 14:18:40 -070016 use_outdoors, true,
Milind Upadhyayf67f67d2022-03-27 14:29:47 -070017 "If set, use the color filters and exposure for an outdoor setting.");
Milind Upadhyay07f6f9e2022-03-18 18:40:34 -070018DEFINE_int32(red_delta, 50, "Required difference between green pixels vs. red");
19DEFINE_int32(blue_delta, -20,
Milind Upadhyay81711112022-03-13 22:59:19 -070020 "Required difference between green pixels vs. blue");
Milind Upadhyayf67f67d2022-03-27 14:29:47 -070021DEFINE_int32(outdoors_red_delta, 70,
22 "Required difference between green pixels vs. red when using "
23 "--use_outdoors");
24DEFINE_int32(outdoors_blue_delta, -10,
25 "Required difference between green pixels vs. blue when using "
26 "--use_outdoors");
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080027
Stephan Pleinesf63bde82024-01-13 15:59:33 -080028namespace y2022::vision {
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080029
Milind Upadhyayec41e132022-02-05 17:14:05 -080030cv::Mat BlobDetector::ThresholdImage(cv::Mat bgr_image) {
31 cv::Mat binarized_image(cv::Size(bgr_image.cols, bgr_image.rows), CV_8UC1);
Milind Upadhyayf67f67d2022-03-27 14:29:47 -070032
33 const int red_delta =
34 (FLAGS_use_outdoors ? FLAGS_outdoors_red_delta : FLAGS_red_delta);
35 const int blue_delta =
36 (FLAGS_use_outdoors ? FLAGS_outdoors_blue_delta : FLAGS_blue_delta);
37
Milind Upadhyayec41e132022-02-05 17:14:05 -080038 for (int row = 0; row < bgr_image.rows; row++) {
39 for (int col = 0; col < bgr_image.cols; col++) {
40 cv::Vec3b pixel = bgr_image.at<cv::Vec3b>(row, col);
Milind Upadhyay81711112022-03-13 22:59:19 -070041 int blue = pixel.val[0];
42 int green = pixel.val[1];
43 int red = pixel.val[2];
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080044 // Simple filter that looks for green pixels sufficiently brigher than
45 // red and blue
Milind Upadhyayf67f67d2022-03-27 14:29:47 -070046 if ((green > blue + blue_delta) && (green > red + red_delta)) {
milind-u61f21e82022-01-23 18:34:11 -080047 binarized_image.at<uint8_t>(row, col) = 255;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080048 } else {
milind-u61f21e82022-01-23 18:34:11 -080049 binarized_image.at<uint8_t>(row, col) = 0;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080050 }
51 }
52 }
53
Milind Upadhyayae998722022-03-13 12:45:55 -070054 // Fill in the contours on the binarized image so that we don't detect
55 // multiple blobs in one
56 const auto blobs = FindBlobs(binarized_image);
57 for (auto it = blobs.begin(); it < blobs.end(); it++) {
58 cv::drawContours(binarized_image, blobs, it - blobs.begin(),
59 cv::Scalar(255), cv::FILLED);
60 }
61
milind-u61f21e82022-01-23 18:34:11 -080062 return binarized_image;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080063}
64
65std::vector<std::vector<cv::Point>> BlobDetector::FindBlobs(
66 cv::Mat binarized_image) {
67 // find the contours (blob outlines)
68 std::vector<std::vector<cv::Point>> contours;
69 std::vector<cv::Vec4i> hierarchy;
70 cv::findContours(binarized_image, contours, hierarchy, cv::RETR_CCOMP,
71 cv::CHAIN_APPROX_SIMPLE);
72
73 return contours;
74}
75
milind-u61f21e82022-01-23 18:34:11 -080076std::vector<BlobDetector::BlobStats> BlobDetector::ComputeStats(
Milind Upadhyayf61e1482022-02-11 20:42:55 -080077 const std::vector<std::vector<cv::Point>> &blobs) {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080078 cv::Mat img = cv::Mat::zeros(640, 480, CV_8UC3);
79
milind-u61f21e82022-01-23 18:34:11 -080080 std::vector<BlobDetector::BlobStats> blob_stats;
81 for (auto blob : blobs) {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080082 // Opencv doesn't have height and width ordered correctly.
83 // The rotated size will only be used after blobs have been filtered, so it
84 // is ok to assume that width is the larger side
85 const cv::Size rotated_rect_size_unordered = cv::minAreaRect(blob).size;
86 const cv::Size rotated_rect_size = {
87 std::max(rotated_rect_size_unordered.width,
88 rotated_rect_size_unordered.height),
89 std::min(rotated_rect_size_unordered.width,
90 rotated_rect_size_unordered.height)};
91 const cv::Size bounding_box_size = cv::boundingRect(blob).size();
92
Milind Upadhyayf61e1482022-02-11 20:42:55 -080093 cv::Moments moments = cv::moments(blob);
milind-u61f21e82022-01-23 18:34:11 -080094
95 const auto centroid =
96 cv::Point(moments.m10 / moments.m00, moments.m01 / moments.m00);
97 const double aspect_ratio =
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080098 static_cast<double>(bounding_box_size.width) / bounding_box_size.height;
milind-u61f21e82022-01-23 18:34:11 -080099 const double area = moments.m00;
Henry Speisere45e7a22022-02-04 23:17:01 -0800100 const size_t num_points = blob.size();
milind-u61f21e82022-01-23 18:34:11 -0800101
Henry Speisere45e7a22022-02-04 23:17:01 -0800102 blob_stats.emplace_back(
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800103 BlobStats{centroid, rotated_rect_size, aspect_ratio, area, num_points});
milind-u61f21e82022-01-23 18:34:11 -0800104 }
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800105
milind-u61f21e82022-01-23 18:34:11 -0800106 return blob_stats;
107}
108
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800109void BlobDetector::FilterBlobs(BlobResult *blob_result) {
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800110 std::vector<std::vector<cv::Point>> filtered_blobs;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800111 std::vector<BlobStats> filtered_stats;
milind-u92195982022-01-22 20:29:31 -0800112
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800113 auto blob_it = blob_result->unfiltered_blobs.begin();
114 auto stats_it = blob_result->blob_stats.begin();
115 while (blob_it < blob_result->unfiltered_blobs.end() &&
116 stats_it < blob_result->blob_stats.end()) {
milind-u61f21e82022-01-23 18:34:11 -0800117 constexpr double kTapeAspectRatio = 5.0 / 2.0;
Milind Upadhyay07f6f9e2022-03-18 18:40:34 -0700118 constexpr double kAspectRatioThreshold = 2.0;
milind-u61f21e82022-01-23 18:34:11 -0800119 constexpr double kMinArea = 10;
Milind Upadhyay07f6f9e2022-03-18 18:40:34 -0700120 constexpr size_t kMinNumPoints = 2;
Milind Upadhyay56414692022-09-24 20:44:16 -0700121 constexpr size_t kMaxNumPoints = 50;
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) &&
Milind Upadhyay56414692022-09-24 20:44:16 -0700128 (stats_it->num_points >= kMinNumPoints) &&
129 (stats_it->num_points <= kMaxNumPoints)) {
milind-u61f21e82022-01-23 18:34:11 -0800130 filtered_blobs.push_back(*blob_it);
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800131 filtered_stats.push_back(*stats_it);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800132 }
milind-u61f21e82022-01-23 18:34:11 -0800133 blob_it++;
134 stats_it++;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800135 }
milind-u92195982022-01-22 20:29:31 -0800136
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800137 // Threshold for mean distance from a blob centroid to a circle.
Austin Schuh0912ea52022-04-16 10:20:53 -0700138 constexpr double kCircleDistanceThreshold = 2.0;
Milind Upadhyayec41e132022-02-05 17:14:05 -0800139 // We should only expect to see blobs between these angles on a circle.
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800140 constexpr double kDegToRad = M_PI / 180.0;
141 constexpr double kMinBlobAngle = 50.0 * kDegToRad;
Milind Upadhyayec41e132022-02-05 17:14:05 -0800142 constexpr double kMaxBlobAngle = M_PI - kMinBlobAngle;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800143 std::vector<std::vector<cv::Point>> blob_circle;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800144 std::vector<BlobStats> blob_circle_stats;
Milind Upadhyayb67c6182022-10-22 13:45:45 -0700145 frc971::vision::Circle circle;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800146
147 // If we see more than this number of blobs after filtering based on
148 // color/size, the circle fit may detect noise so just return no blobs.
Milind Upadhyay2b4404c2022-02-04 21:20:57 -0800149 constexpr size_t kMinFilteredBlobs = 3;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800150 constexpr size_t kMaxFilteredBlobs = 50;
Milind Upadhyay2b4404c2022-02-04 21:20:57 -0800151 if (filtered_blobs.size() >= kMinFilteredBlobs &&
152 filtered_blobs.size() <= kMaxFilteredBlobs) {
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800153 constexpr size_t kRansacIterations = 15;
154 for (size_t i = 0; i < kRansacIterations; i++) {
155 // Pick 3 random blobs and see how many fit on their circle
156 const size_t j = std::rand() % filtered_blobs.size();
157 const size_t k = std::rand() % filtered_blobs.size();
158 const size_t l = std::rand() % filtered_blobs.size();
159
160 // Restart if the random indices clash
161 if ((j == k) || (j == l) || (k == l)) {
162 i--;
163 continue;
164 }
165
166 std::vector<std::vector<cv::Point>> current_blobs{
167 filtered_blobs[j], filtered_blobs[k], filtered_blobs[l]};
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800168 std::vector<BlobStats> current_stats{filtered_stats[j], filtered_stats[k],
169 filtered_stats[l]};
Milind Upadhyayb67c6182022-10-22 13:45:45 -0700170 const std::optional<frc971::vision::Circle> current_circle =
171 frc971::vision::Circle::Fit({current_stats[0].centroid,
172 current_stats[1].centroid,
173 current_stats[2].centroid});
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800174
175 // Make sure that a circle could be created from the points
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800176 if (!current_circle) {
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800177 continue;
178 }
179
Milind Upadhyayec41e132022-02-05 17:14:05 -0800180 // Only try to fit points to this circle if all of these are between
181 // certain angles.
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800182 if (current_circle->InAngleRange(current_stats[0].centroid, kMinBlobAngle,
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800183 kMaxBlobAngle) &&
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800184 current_circle->InAngleRange(current_stats[1].centroid, kMinBlobAngle,
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800185 kMaxBlobAngle) &&
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800186 current_circle->InAngleRange(current_stats[2].centroid, kMinBlobAngle,
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800187 kMaxBlobAngle)) {
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800188 for (size_t m = 0; m < filtered_blobs.size(); m++) {
189 // Add this blob to the list if it is close to the circle, is on the
190 // top half, and isn't one of the other blobs
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800191 if ((m != j) && (m != k) && (m != l) &&
192 current_circle->InAngleRange(filtered_stats[m].centroid,
193 kMinBlobAngle, kMaxBlobAngle) &&
194 (current_circle->DistanceTo(filtered_stats[m].centroid) <
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800195 kCircleDistanceThreshold)) {
196 current_blobs.emplace_back(filtered_blobs[m]);
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800197 current_stats.emplace_back(filtered_stats[m]);
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800198 }
199 }
200
201 if (current_blobs.size() > blob_circle.size()) {
202 blob_circle = current_blobs;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800203 blob_circle_stats = current_stats;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800204 circle = *current_circle;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800205 }
206 }
207 }
208 }
209
210 cv::Point avg_centroid(-1, -1);
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800211 if (blob_circle.size() > 0) {
212 for (const auto &stats : blob_circle_stats) {
213 avg_centroid.x += stats.centroid.x;
214 avg_centroid.y += stats.centroid.y;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800215 }
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800216 avg_centroid.x /= blob_circle_stats.size();
217 avg_centroid.y /= blob_circle_stats.size();
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800218 }
219
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800220 blob_result->filtered_blobs = blob_circle;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800221 blob_result->filtered_stats = blob_circle_stats;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800222 blob_result->centroid = avg_centroid;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800223}
224
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800225void BlobDetector::DrawBlobs(const BlobResult &blob_result,
226 cv::Mat view_image) {
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800227 CHECK_GT(view_image.cols, 0);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800228 if (blob_result.unfiltered_blobs.size() > 0) {
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800229 // Draw blobs unfilled, with red color border
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800230 cv::drawContours(view_image, blob_result.unfiltered_blobs, -1,
231 cv::Scalar(0, 0, 255), 0);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800232 }
233
James Kuszmauld230d7a2022-03-06 15:00:43 -0800234 if (blob_result.filtered_blobs.size() > 0) {
235 cv::drawContours(view_image, blob_result.filtered_blobs, -1,
236 cv::Scalar(0, 100, 0), cv::FILLED);
237 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800238
Milind Upadhyay2da80bb2022-03-12 22:54:35 -0800239 for (const auto &blob : blob_result.filtered_blobs) {
240 cv::polylines(view_image, blob, true, cv::Scalar(0, 255, 0));
241 }
242
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800243 static constexpr double kCircleRadius = 2.0;
milind-u92195982022-01-22 20:29:31 -0800244 // Draw blob centroids
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800245 for (auto stats : blob_result.blob_stats) {
246 cv::circle(view_image, stats.centroid, kCircleRadius,
247 cv::Scalar(0, 215, 255), cv::FILLED);
248 }
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800249 for (auto stats : blob_result.filtered_stats) {
250 cv::circle(view_image, stats.centroid, kCircleRadius, cv::Scalar(0, 255, 0),
milind-u61f21e82022-01-23 18:34:11 -0800251 cv::FILLED);
252 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800253}
254
Milind Upadhyayec41e132022-02-05 17:14:05 -0800255void BlobDetector::ExtractBlobs(cv::Mat bgr_image,
Milind Upadhyay25610d22022-02-07 15:35:26 -0800256 BlobDetector::BlobResult *blob_result) {
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800257 auto start = aos::monotonic_clock::now();
Milind Upadhyayec41e132022-02-05 17:14:05 -0800258 blob_result->binarized_image = ThresholdImage(bgr_image);
Milind Upadhyay25610d22022-02-07 15:35:26 -0800259 blob_result->unfiltered_blobs = FindBlobs(blob_result->binarized_image);
260 blob_result->blob_stats = ComputeStats(blob_result->unfiltered_blobs);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800261 FilterBlobs(blob_result);
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800262 auto end = aos::monotonic_clock::now();
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800263 VLOG(1) << "Blob detection elapsed time: "
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800264 << std::chrono::duration<double, std::milli>(end - start).count()
265 << " ms";
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800266}
267
Stephan Pleinesf63bde82024-01-13 15:59:33 -0800268} // namespace y2022::vision