blob: 2d5ae63217cbe2d2daf72311db611227abd001c0 [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");
16DEFINE_uint64(blue_delta, 50,
17 "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-u61f21e82022-01-23 18:34:11 -080055 return binarized_image;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080056}
57
58std::vector<std::vector<cv::Point>> BlobDetector::FindBlobs(
59 cv::Mat binarized_image) {
60 // find the contours (blob outlines)
61 std::vector<std::vector<cv::Point>> contours;
62 std::vector<cv::Vec4i> hierarchy;
63 cv::findContours(binarized_image, contours, hierarchy, cv::RETR_CCOMP,
64 cv::CHAIN_APPROX_SIMPLE);
65
66 return contours;
67}
68
milind-u61f21e82022-01-23 18:34:11 -080069std::vector<BlobDetector::BlobStats> BlobDetector::ComputeStats(
Milind Upadhyayf61e1482022-02-11 20:42:55 -080070 const std::vector<std::vector<cv::Point>> &blobs) {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080071 cv::Mat img = cv::Mat::zeros(640, 480, CV_8UC3);
72
milind-u61f21e82022-01-23 18:34:11 -080073 std::vector<BlobDetector::BlobStats> blob_stats;
74 for (auto blob : blobs) {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080075 // Opencv doesn't have height and width ordered correctly.
76 // The rotated size will only be used after blobs have been filtered, so it
77 // is ok to assume that width is the larger side
78 const cv::Size rotated_rect_size_unordered = cv::minAreaRect(blob).size;
79 const cv::Size rotated_rect_size = {
80 std::max(rotated_rect_size_unordered.width,
81 rotated_rect_size_unordered.height),
82 std::min(rotated_rect_size_unordered.width,
83 rotated_rect_size_unordered.height)};
84 const cv::Size bounding_box_size = cv::boundingRect(blob).size();
85
Milind Upadhyayf61e1482022-02-11 20:42:55 -080086 cv::Moments moments = cv::moments(blob);
milind-u61f21e82022-01-23 18:34:11 -080087
88 const auto centroid =
89 cv::Point(moments.m10 / moments.m00, moments.m01 / moments.m00);
90 const double aspect_ratio =
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080091 static_cast<double>(bounding_box_size.width) / bounding_box_size.height;
milind-u61f21e82022-01-23 18:34:11 -080092 const double area = moments.m00;
Henry Speisere45e7a22022-02-04 23:17:01 -080093 const size_t num_points = blob.size();
milind-u61f21e82022-01-23 18:34:11 -080094
Henry Speisere45e7a22022-02-04 23:17:01 -080095 blob_stats.emplace_back(
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080096 BlobStats{centroid, rotated_rect_size, aspect_ratio, area, num_points});
milind-u61f21e82022-01-23 18:34:11 -080097 }
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080098
milind-u61f21e82022-01-23 18:34:11 -080099 return blob_stats;
100}
101
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800102void BlobDetector::FilterBlobs(BlobResult *blob_result) {
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800103 std::vector<std::vector<cv::Point>> filtered_blobs;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800104 std::vector<BlobStats> filtered_stats;
milind-u92195982022-01-22 20:29:31 -0800105
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800106 auto blob_it = blob_result->unfiltered_blobs.begin();
107 auto stats_it = blob_result->blob_stats.begin();
108 while (blob_it < blob_result->unfiltered_blobs.end() &&
109 stats_it < blob_result->blob_stats.end()) {
milind-u61f21e82022-01-23 18:34:11 -0800110 constexpr double kTapeAspectRatio = 5.0 / 2.0;
Milind Upadhyayec41e132022-02-05 17:14:05 -0800111 constexpr double kAspectRatioThreshold = 1.6;
milind-u61f21e82022-01-23 18:34:11 -0800112 constexpr double kMinArea = 10;
Milind Upadhyayec41e132022-02-05 17:14:05 -0800113 constexpr size_t kMinNumPoints = 6;
milind-u92195982022-01-22 20:29:31 -0800114
milind-u61f21e82022-01-23 18:34:11 -0800115 // Remove all blobs that are at the bottom of the image, have a different
Milind Upadhyayec41e132022-02-05 17:14:05 -0800116 // aspect ratio than the tape, or have too little area or points.
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800117 if ((std::abs(1.0 - kTapeAspectRatio / stats_it->aspect_ratio) <
milind-u61f21e82022-01-23 18:34:11 -0800118 kAspectRatioThreshold) &&
Milind Upadhyayec41e132022-02-05 17:14:05 -0800119 (stats_it->area >= kMinArea) &&
120 (stats_it->num_points >= kMinNumPoints)) {
milind-u61f21e82022-01-23 18:34:11 -0800121 filtered_blobs.push_back(*blob_it);
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800122 filtered_stats.push_back(*stats_it);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800123 }
milind-u61f21e82022-01-23 18:34:11 -0800124 blob_it++;
125 stats_it++;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800126 }
milind-u92195982022-01-22 20:29:31 -0800127
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800128 // Threshold for mean distance from a blob centroid to a circle.
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800129 constexpr double kCircleDistanceThreshold = 10.0;
Milind Upadhyayec41e132022-02-05 17:14:05 -0800130 // We should only expect to see blobs between these angles on a circle.
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800131 constexpr double kDegToRad = M_PI / 180.0;
132 constexpr double kMinBlobAngle = 50.0 * kDegToRad;
Milind Upadhyayec41e132022-02-05 17:14:05 -0800133 constexpr double kMaxBlobAngle = M_PI - kMinBlobAngle;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800134 std::vector<std::vector<cv::Point>> blob_circle;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800135 std::vector<BlobStats> blob_circle_stats;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800136 Circle circle;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800137
138 // If we see more than this number of blobs after filtering based on
139 // color/size, the circle fit may detect noise so just return no blobs.
Milind Upadhyay2b4404c2022-02-04 21:20:57 -0800140 constexpr size_t kMinFilteredBlobs = 3;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800141 constexpr size_t kMaxFilteredBlobs = 50;
Milind Upadhyay2b4404c2022-02-04 21:20:57 -0800142 if (filtered_blobs.size() >= kMinFilteredBlobs &&
143 filtered_blobs.size() <= kMaxFilteredBlobs) {
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800144 constexpr size_t kRansacIterations = 15;
145 for (size_t i = 0; i < kRansacIterations; i++) {
146 // Pick 3 random blobs and see how many fit on their circle
147 const size_t j = std::rand() % filtered_blobs.size();
148 const size_t k = std::rand() % filtered_blobs.size();
149 const size_t l = std::rand() % filtered_blobs.size();
150
151 // Restart if the random indices clash
152 if ((j == k) || (j == l) || (k == l)) {
153 i--;
154 continue;
155 }
156
157 std::vector<std::vector<cv::Point>> current_blobs{
158 filtered_blobs[j], filtered_blobs[k], filtered_blobs[l]};
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800159 std::vector<BlobStats> current_stats{filtered_stats[j], filtered_stats[k],
160 filtered_stats[l]};
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800161 const std::optional<Circle> current_circle =
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800162 Circle::Fit({current_stats[0].centroid, current_stats[1].centroid,
163 current_stats[2].centroid});
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800164
165 // Make sure that a circle could be created from the points
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800166 if (!current_circle) {
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800167 continue;
168 }
169
Milind Upadhyayec41e132022-02-05 17:14:05 -0800170 // Only try to fit points to this circle if all of these are between
171 // certain angles.
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800172 if (current_circle->InAngleRange(current_stats[0].centroid, kMinBlobAngle,
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800173 kMaxBlobAngle) &&
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800174 current_circle->InAngleRange(current_stats[1].centroid, kMinBlobAngle,
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800175 kMaxBlobAngle) &&
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800176 current_circle->InAngleRange(current_stats[2].centroid, kMinBlobAngle,
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800177 kMaxBlobAngle)) {
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800178 for (size_t m = 0; m < filtered_blobs.size(); m++) {
179 // Add this blob to the list if it is close to the circle, is on the
180 // top half, and isn't one of the other blobs
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800181 if ((m != j) && (m != k) && (m != l) &&
182 current_circle->InAngleRange(filtered_stats[m].centroid,
183 kMinBlobAngle, kMaxBlobAngle) &&
184 (current_circle->DistanceTo(filtered_stats[m].centroid) <
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800185 kCircleDistanceThreshold)) {
186 current_blobs.emplace_back(filtered_blobs[m]);
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800187 current_stats.emplace_back(filtered_stats[m]);
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800188 }
189 }
190
191 if (current_blobs.size() > blob_circle.size()) {
192 blob_circle = current_blobs;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800193 blob_circle_stats = current_stats;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800194 circle = *current_circle;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800195 }
196 }
197 }
198 }
199
200 cv::Point avg_centroid(-1, -1);
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800201 if (blob_circle.size() > 0) {
202 for (const auto &stats : blob_circle_stats) {
203 avg_centroid.x += stats.centroid.x;
204 avg_centroid.y += stats.centroid.y;
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800205 }
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800206 avg_centroid.x /= blob_circle_stats.size();
207 avg_centroid.y /= blob_circle_stats.size();
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800208 }
209
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800210 blob_result->filtered_blobs = blob_circle;
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800211 blob_result->filtered_stats = blob_circle_stats;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800212 blob_result->centroid = avg_centroid;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800213}
214
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800215void BlobDetector::DrawBlobs(const BlobResult &blob_result,
216 cv::Mat view_image) {
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800217 CHECK_GT(view_image.cols, 0);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800218 if (blob_result.unfiltered_blobs.size() > 0) {
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800219 // Draw blobs unfilled, with red color border
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800220 cv::drawContours(view_image, blob_result.unfiltered_blobs, -1,
221 cv::Scalar(0, 0, 255), 0);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800222 }
223
James Kuszmauld230d7a2022-03-06 15:00:43 -0800224 if (blob_result.filtered_blobs.size() > 0) {
225 cv::drawContours(view_image, blob_result.filtered_blobs, -1,
226 cv::Scalar(0, 100, 0), cv::FILLED);
227 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800228
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800229 static constexpr double kCircleRadius = 2.0;
milind-u92195982022-01-22 20:29:31 -0800230 // Draw blob centroids
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800231 for (auto stats : blob_result.blob_stats) {
232 cv::circle(view_image, stats.centroid, kCircleRadius,
233 cv::Scalar(0, 215, 255), cv::FILLED);
234 }
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800235 for (auto stats : blob_result.filtered_stats) {
236 cv::circle(view_image, stats.centroid, kCircleRadius, cv::Scalar(0, 255, 0),
milind-u61f21e82022-01-23 18:34:11 -0800237 cv::FILLED);
238 }
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800239
240 // Draw average centroid
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800241 cv::circle(view_image, blob_result.centroid, kCircleRadius,
242 cv::Scalar(255, 255, 0), cv::FILLED);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800243}
244
Milind Upadhyayec41e132022-02-05 17:14:05 -0800245void BlobDetector::ExtractBlobs(cv::Mat bgr_image,
Milind Upadhyay25610d22022-02-07 15:35:26 -0800246 BlobDetector::BlobResult *blob_result) {
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800247 auto start = aos::monotonic_clock::now();
Milind Upadhyayec41e132022-02-05 17:14:05 -0800248 blob_result->binarized_image = ThresholdImage(bgr_image);
Milind Upadhyay25610d22022-02-07 15:35:26 -0800249 blob_result->unfiltered_blobs = FindBlobs(blob_result->binarized_image);
250 blob_result->blob_stats = ComputeStats(blob_result->unfiltered_blobs);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800251 FilterBlobs(blob_result);
Milind Upadhyaye7aa40c2022-01-29 22:36:21 -0800252 auto end = aos::monotonic_clock::now();
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800253 VLOG(1) << "Blob detection elapsed time: "
Jim Ostrowskifec0c332022-02-06 23:28:26 -0800254 << std::chrono::duration<double, std::milli>(end - start).count()
255 << " ms";
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800256}
257
258} // namespace vision
259} // namespace y2022