blob: 8d9226574e4e24719b1d7974196754cb10377e94 [file] [log] [blame]
Parker Schuh2a1447c2019-02-17 00:25:29 -08001#include "y2019/vision/target_finder.h"
2
3#include "aos/vision/blob/hierarchical_contour_merge.h"
4
5using namespace aos::vision;
6
7namespace y2019 {
8namespace vision {
9
Austin Schuh4d6e9bd2019-03-08 19:54:17 -080010TargetFinder::TargetFinder() : target_template_(Target::MakeTemplate()) {}
Parker Schuh2a1447c2019-02-17 00:25:29 -080011
12aos::vision::RangeImage TargetFinder::Threshold(aos::vision::ImagePtr image) {
13 const uint8_t threshold_value = GetThresholdValue();
14 return aos::vision::DoThreshold(image, [&](aos::vision::PixelRef &px) {
15 if (px.g > threshold_value && px.b > threshold_value &&
16 px.r > threshold_value) {
17 return true;
18 }
19 return false;
20 });
21}
22
23// Filter blobs on size.
24void TargetFinder::PreFilter(BlobList *imgs) {
25 imgs->erase(
26 std::remove_if(imgs->begin(), imgs->end(),
27 [](RangeImage &img) {
28 // We can drop images with a small number of
29 // pixels, but images
30 // must be over 20px or the math will have issues.
31 return (img.npixels() < 100 || img.height() < 25);
32 }),
33 imgs->end());
34}
35
Ben Fredricksonf7b68522019-03-02 21:19:42 -080036ContourNode* TargetFinder::GetContour(const RangeImage &blob) {
37 alloc_.reset();
38 return RangeImgToContour(blob, &alloc_);
39}
40
Ben Fredricksonec575822019-03-02 22:03:20 -080041// TODO(ben): These values will be moved into the constants.h file.
Ben Fredricksonf7b68522019-03-02 21:19:42 -080042namespace {
43
Ben Fredricksonec575822019-03-02 22:03:20 -080044constexpr double f_x = 481.4957;
45constexpr double c_x = 341.215;
46constexpr double f_y = 484.314;
47constexpr double c_y = 251.29;
Ben Fredricksonf7b68522019-03-02 21:19:42 -080048
Ben Fredricksonec575822019-03-02 22:03:20 -080049constexpr double f_x_prime = 363.1424;
50constexpr double c_x_prime = 337.9895;
51constexpr double f_y_prime = 366.4837;
52constexpr double c_y_prime = 240.0702;
Ben Fredricksonf7b68522019-03-02 21:19:42 -080053
Ben Fredricksonec575822019-03-02 22:03:20 -080054constexpr double k_1 = -0.2739;
55constexpr double k_2 = 0.01583;
56constexpr double k_3 = 0.04201;
Ben Fredricksonf7b68522019-03-02 21:19:42 -080057
58constexpr int iterations = 7;
59
60}
61
Austin Schuhe5015972019-03-09 17:47:34 -080062::Eigen::Vector2f UnWarpPoint(const Point point) {
Ben Fredricksonec575822019-03-02 22:03:20 -080063 const double x0 = ((double)point.x - c_x) / f_x;
64 const double y0 = ((double)point.y - c_y) / f_y;
Ben Fredricksonf7b68522019-03-02 21:19:42 -080065 double x = x0;
66 double y = y0;
67 for (int i = 0; i < iterations; i++) {
68 const double r_sqr = x * x + y * y;
69 const double coeff =
Ben Fredricksonec575822019-03-02 22:03:20 -080070 1.0 + r_sqr * (k_1 + k_2 * r_sqr * (1.0 + k_3 * r_sqr));
Ben Fredricksonf7b68522019-03-02 21:19:42 -080071 x = x0 / coeff;
72 y = y0 / coeff;
73 }
Austin Schuhe5015972019-03-09 17:47:34 -080074 const double nx = x * f_x_prime + c_x_prime;
75 const double ny = y * f_y_prime + c_y_prime;
76 return ::Eigen::Vector2f(nx, ny);
Ben Fredricksonf7b68522019-03-02 21:19:42 -080077}
78
Austin Schuhe5015972019-03-09 17:47:34 -080079::std::vector<::Eigen::Vector2f> TargetFinder::UnWarpContour(
80 ContourNode *start) const {
81 ::std::vector<::Eigen::Vector2f> result;
Ben Fredricksonf7b68522019-03-02 21:19:42 -080082 ContourNode *node = start;
83 while (node->next != start) {
Austin Schuhe5015972019-03-09 17:47:34 -080084 result.push_back(UnWarpPoint(node->pt));
Ben Fredricksonf7b68522019-03-02 21:19:42 -080085 node = node->next;
86 }
Austin Schuhe5015972019-03-09 17:47:34 -080087 result.push_back(UnWarpPoint(node->pt));
88 return result;
Ben Fredricksonf7b68522019-03-02 21:19:42 -080089}
90
Parker Schuh2a1447c2019-02-17 00:25:29 -080091// TODO: Try hierarchical merge for this.
92// Convert blobs into polygons.
93std::vector<aos::vision::Segment<2>> TargetFinder::FillPolygon(
Austin Schuhe5015972019-03-09 17:47:34 -080094 const ::std::vector<::Eigen::Vector2f> &contour, bool verbose) {
Parker Schuh2a1447c2019-02-17 00:25:29 -080095 if (verbose) printf("Process Polygon.\n");
Parker Schuh2a1447c2019-02-17 00:25:29 -080096
Austin Schuhe5015972019-03-09 17:47:34 -080097 ::std::vector<::Eigen::Vector2f> slopes;
Parker Schuh2a1447c2019-02-17 00:25:29 -080098
99 // Collect all slopes from the contour.
Austin Schuhe5015972019-03-09 17:47:34 -0800100 ::Eigen::Vector2f previous_point = contour[0];
101 for (size_t i = 0; i < contour.size(); ++i) {
102 ::Eigen::Vector2f next_point = contour[(i + 1) % contour.size()];
Parker Schuh2a1447c2019-02-17 00:25:29 -0800103
Austin Schuhe5015972019-03-09 17:47:34 -0800104 slopes.push_back(next_point - previous_point);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800105
Austin Schuhe5015972019-03-09 17:47:34 -0800106 previous_point = next_point;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800107 }
108
Austin Schuhe5015972019-03-09 17:47:34 -0800109 const int num_points = slopes.size();
110 auto get_pt = [&slopes, num_points](int i) {
111 return slopes[(i + num_points * 2) % num_points];
Austin Schuh335eef12019-03-02 17:04:17 -0800112 };
Parker Schuh2a1447c2019-02-17 00:25:29 -0800113
Austin Schuh6a484962019-03-09 21:51:27 -0800114 // Bigger objects should be more filtered. Filter roughly proportional to the
115 // perimeter of the object.
116 const int range = slopes.size() / 50;
117 if (verbose) printf("Corner range: %d.\n", range);
118
Austin Schuhe5015972019-03-09 17:47:34 -0800119 ::std::vector<::Eigen::Vector2f> filtered_slopes = slopes;
Austin Schuh335eef12019-03-02 17:04:17 -0800120 // Three box filter makith a guassian?
121 // Run gaussian filter over the slopes 3 times. That'll get us pretty close
122 // to running a gausian over it.
123 for (int k = 0; k < 3; ++k) {
Austin Schuh6a484962019-03-09 21:51:27 -0800124 const int window_size = ::std::max(2, range);
Austin Schuhe5015972019-03-09 17:47:34 -0800125 for (size_t i = 0; i < slopes.size(); ++i) {
126 ::Eigen::Vector2f a = ::Eigen::Vector2f::Zero();
Parker Schuh2a1447c2019-02-17 00:25:29 -0800127 for (int j = -window_size; j <= window_size; ++j) {
Austin Schuhe5015972019-03-09 17:47:34 -0800128 ::Eigen::Vector2f p = get_pt(j + i);
129 a += p;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800130 }
Austin Schuhe5015972019-03-09 17:47:34 -0800131 a /= (window_size * 2 + 1);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800132
Austin Schuhe5015972019-03-09 17:47:34 -0800133 filtered_slopes[i] = a;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800134 }
Austin Schuhe5015972019-03-09 17:47:34 -0800135 slopes = filtered_slopes;
Austin Schuh335eef12019-03-02 17:04:17 -0800136 }
Austin Schuh6a484962019-03-09 21:51:27 -0800137 if (verbose) printf("Point count: %zu.\n", slopes.size());
Parker Schuh2a1447c2019-02-17 00:25:29 -0800138
Austin Schuh6a484962019-03-09 21:51:27 -0800139 ::std::vector<float> corner_metric(slopes.size(), 0.0);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800140
Austin Schuh6a484962019-03-09 21:51:27 -0800141 for (size_t i = 0; i < slopes.size(); ++i) {
142 const ::Eigen::Vector2f a = get_pt(i - ::std::max(3, range));
143 const ::Eigen::Vector2f b = get_pt(i + ::std::max(3, range));
144 corner_metric[i] = (a - b).squaredNorm();
145 }
146
147 // We want to find the Nth highest peaks.
148 // Clever algorithm: Find the highest point. Then, walk forwards and
149 // backwards to find the next valley each direction which is over x% lower
150 // than the peak.
151 // We want to ignore those points in the future. Set them to 0.
152 // Repeat until we've found the Nth highest peak.
Parker Schuh2a1447c2019-02-17 00:25:29 -0800153
154 // Find all centers of corners.
Austin Schuhe5015972019-03-09 17:47:34 -0800155 // Because they round, multiple slopes may be a corner.
156 ::std::vector<size_t> edges;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800157
Austin Schuh6a484962019-03-09 21:51:27 -0800158 ::std::vector<size_t> peaks;
159
160 constexpr float peak_acceptance_ratio = 0.16;
161 constexpr float valley_ratio = 0.75;
162
163 float highest_peak_value = 0.0;
164
165 // Nth higest points.
166 for (int j = 0; j < 5; ++j) {
167 const ::std::vector<float>::iterator max_element =
168 ::std::max_element(corner_metric.begin(), corner_metric.end());
169 const size_t highest_index =
170 ::std::distance(corner_metric.begin(), max_element);
171 const float max_value = *max_element;
172 if (j == 0) {
173 highest_peak_value = max_value;
174 }
175 if (max_value < highest_peak_value * peak_acceptance_ratio && j == 4) {
176 if (verbose)
177 printf("Rejecting index: %zu, %f (%f %%)\n", highest_index, max_value,
178 max_value / highest_peak_value);
179 break;
180 }
181 const float valley_value = max_value * valley_ratio;
182
183 if (verbose)
184 printf("Highest index: %zu, %f (%f %%)\n", highest_index, max_value,
185 max_value / highest_peak_value);
186
187 {
188 float min_value = max_value;
189 size_t fwd_index = (highest_index + 1) % corner_metric.size();
190 while (true) {
191 const float current_value = corner_metric[fwd_index];
192 min_value = ::std::min(current_value, min_value);
193
194 if (current_value == 0.0 ||
195 (min_value < valley_value && current_value > min_value)) {
196 break;
197 }
198 // Kill!!!
199 corner_metric[fwd_index] = 0.0;
200
201 fwd_index = (fwd_index + 1) % corner_metric.size();
Parker Schuh2a1447c2019-02-17 00:25:29 -0800202 }
203 }
Austin Schuh6a484962019-03-09 21:51:27 -0800204
205 {
206 float min_value = max_value;
207 size_t rev_index =
208 (highest_index - 1 + corner_metric.size()) % corner_metric.size();
209 while (true) {
210 const float current_value = corner_metric[rev_index];
211 min_value = ::std::min(current_value, min_value);
212
213 if (current_value == 0.0 ||
214 (min_value < valley_value && current_value > min_value)) {
215 break;
216 }
217 // Kill!!!
218 corner_metric[rev_index] = 0.0;
219
220 rev_index =
221 (rev_index - 1 + corner_metric.size()) % corner_metric.size();
222 }
Parker Schuh2a1447c2019-02-17 00:25:29 -0800223 }
Austin Schuh6a484962019-03-09 21:51:27 -0800224
225 *max_element = 0.0;
226 edges.push_back(highest_index);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800227 }
228
Austin Schuh6a484962019-03-09 21:51:27 -0800229 ::std::sort(edges.begin(), edges.end());
Parker Schuh2a1447c2019-02-17 00:25:29 -0800230
231 if (verbose) printf("Edge Count (%zu).\n", edges.size());
232
Parker Schuh2a1447c2019-02-17 00:25:29 -0800233 // Run best-fits over each line segment.
Austin Schuhe5015972019-03-09 17:47:34 -0800234 ::std::vector<Segment<2>> seg_list;
Austin Schuh6a484962019-03-09 21:51:27 -0800235 if (edges.size() >= 3) {
Austin Schuhe5015972019-03-09 17:47:34 -0800236 for (size_t i = 0; i < edges.size(); ++i) {
237 // Include the corners in both line fits.
238 const size_t segment_start_index = edges[i];
239 const size_t segment_end_index =
240 (edges[(i + 1) % edges.size()] + 1) % contour.size();
Parker Schuh2a1447c2019-02-17 00:25:29 -0800241 float mx = 0.0;
242 float my = 0.0;
243 int n = 0;
Austin Schuhe5015972019-03-09 17:47:34 -0800244 for (size_t j = segment_start_index; j != segment_end_index;
245 (j = (j + 1) % contour.size())) {
246 mx += contour[j].x();
247 my += contour[j].y();
Parker Schuh2a1447c2019-02-17 00:25:29 -0800248 ++n;
249 // (x - [x] / N) ** 2 = [x * x] - 2 * [x] * [x] / N + [x] * [x] / N / N;
250 }
251 mx /= n;
252 my /= n;
253
254 float xx = 0.0;
255 float xy = 0.0;
256 float yy = 0.0;
Austin Schuhe5015972019-03-09 17:47:34 -0800257 for (size_t j = segment_start_index; j != segment_end_index;
258 (j = (j + 1) % contour.size())) {
259 const float x = contour[j].x() - mx;
260 const float y = contour[j].y() - my;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800261 xx += x * x;
262 xy += x * y;
263 yy += y * y;
264 }
265
266 // TODO: Extract common to hierarchical merge.
Austin Schuh335eef12019-03-02 17:04:17 -0800267 const float neg_b_over_2 = (xx + yy) / 2.0;
268 const float c = (xx * yy - xy * xy);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800269
Austin Schuh335eef12019-03-02 17:04:17 -0800270 const float sqr = sqrt(neg_b_over_2 * neg_b_over_2 - c);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800271
272 {
Austin Schuh335eef12019-03-02 17:04:17 -0800273 const float lam = neg_b_over_2 + sqr;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800274 float x = xy;
275 float y = lam - xx;
276
Austin Schuh335eef12019-03-02 17:04:17 -0800277 const float norm = hypot(x, y);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800278 x /= norm;
279 y /= norm;
280
281 seg_list.push_back(
282 Segment<2>(Vector<2>(mx, my), Vector<2>(mx + x, my + y)));
283 }
284
285 /* Characteristic polynomial
286 1 lam^2 - (xx + yy) lam + (xx * yy - xy * xy) = 0
287
288 [a b]
289 [c d]
290
291 // covariance matrix.
292 [xx xy] [nx]
293 [xy yy] [ny]
294 */
295 }
296 }
297 if (verbose) printf("Poly Count (%zu).\n", seg_list.size());
298 return seg_list;
299}
300
301// Convert segments into target components (left or right)
302std::vector<TargetComponent> TargetFinder::FillTargetComponentList(
303 const std::vector<std::vector<Segment<2>>> &seg_list) {
304 std::vector<TargetComponent> list;
305 TargetComponent new_target;
Austin Schuh335eef12019-03-02 17:04:17 -0800306 for (const std::vector<Segment<2>> &poly : seg_list) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800307 // Reject missized pollygons for now. Maybe rectify them here in the future;
Austin Schuh9f859ca2019-03-06 20:46:01 -0800308 if (poly.size() != 4) {
309 continue;
310 }
Parker Schuh2a1447c2019-02-17 00:25:29 -0800311 std::vector<Vector<2>> corners;
312 for (size_t i = 0; i < 4; ++i) {
Austin Schuh9f859ca2019-03-06 20:46:01 -0800313 Vector<2> corner = poly[i].Intersect(poly[(i + 1) % 4]);
314 if (::std::isnan(corner.x()) || ::std::isnan(corner.y())) {
315 break;
316 }
317 corners.push_back(corner);
318 }
319 if (corners.size() != 4) {
320 continue;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800321 }
322
323 // Select the closest two points. Short side of the rectangle.
324 double min_dist = -1;
325 std::pair<size_t, size_t> closest;
326 for (size_t i = 0; i < 4; ++i) {
327 size_t next = (i + 1) % 4;
328 double nd = corners[i].SquaredDistanceTo(corners[next]);
329 if (min_dist == -1 || nd < min_dist) {
330 min_dist = nd;
331 closest.first = i;
332 closest.second = next;
333 }
334 }
335
336 // Verify our top is above the bottom.
337 size_t bot_index = closest.first;
338 size_t top_index = (closest.first + 2) % 4;
339 if (corners[top_index].y() < corners[bot_index].y()) {
340 closest.first = top_index;
341 closest.second = (top_index + 1) % 4;
342 }
343
344 // Find the major axis.
345 size_t far_first = (closest.first + 2) % 4;
346 size_t far_second = (closest.second + 2) % 4;
347 Segment<2> major_axis(
348 (corners[closest.first] + corners[closest.second]) * 0.5,
349 (corners[far_first] + corners[far_second]) * 0.5);
350 if (major_axis.AsVector().AngleToZero() > M_PI / 180.0 * 120.0 ||
351 major_axis.AsVector().AngleToZero() < M_PI / 180.0 * 60.0) {
352 // Target is angled way too much, drop it.
353 continue;
354 }
355
356 // organize the top points.
357 Vector<2> topA = corners[closest.first] - major_axis.B();
358 new_target.major_axis = major_axis;
359 if (major_axis.AsVector().AngleToZero() > M_PI / 2.0) {
360 // We have a left target since we are leaning positive.
361 new_target.is_right = false;
362 if (topA.AngleTo(major_axis.AsVector()) > 0.0) {
363 // And our A point is left of the major axis.
364 new_target.inside = corners[closest.second];
365 new_target.top = corners[closest.first];
366 } else {
367 // our A point is to the right of the major axis.
368 new_target.inside = corners[closest.first];
369 new_target.top = corners[closest.second];
370 }
371 } else {
372 // We have a right target since we are leaning negative.
373 new_target.is_right = true;
374 if (topA.AngleTo(major_axis.AsVector()) > 0.0) {
375 // And our A point is left of the major axis.
376 new_target.inside = corners[closest.first];
377 new_target.top = corners[closest.second];
378 } else {
379 // our A point is to the right of the major axis.
380 new_target.inside = corners[closest.second];
381 new_target.top = corners[closest.first];
382 }
383 }
384
385 // organize the top points.
386 Vector<2> botA = corners[far_first] - major_axis.A();
387 if (major_axis.AsVector().AngleToZero() > M_PI / 2.0) {
388 // We have a right target since we are leaning positive.
389 if (botA.AngleTo(major_axis.AsVector()) < M_PI) {
390 // And our A point is left of the major axis.
391 new_target.outside = corners[far_second];
392 new_target.bottom = corners[far_first];
393 } else {
394 // our A point is to the right of the major axis.
395 new_target.outside = corners[far_first];
396 new_target.bottom = corners[far_second];
397 }
398 } else {
399 // We have a left target since we are leaning negative.
400 if (botA.AngleTo(major_axis.AsVector()) < M_PI) {
401 // And our A point is left of the major axis.
402 new_target.outside = corners[far_first];
403 new_target.bottom = corners[far_second];
404 } else {
405 // our A point is to the right of the major axis.
406 new_target.outside = corners[far_second];
407 new_target.bottom = corners[far_first];
408 }
409 }
410
411 // This piece of the target should be ready now.
412 list.emplace_back(new_target);
413 }
414
415 return list;
416}
417
418// Match components into targets.
419std::vector<Target> TargetFinder::FindTargetsFromComponents(
420 const std::vector<TargetComponent> component_list, bool verbose) {
421 std::vector<Target> target_list;
422 using namespace aos::vision;
423 if (component_list.size() < 2) {
424 // We don't enough parts for a target.
425 return target_list;
426 }
427
428 for (size_t i = 0; i < component_list.size(); i++) {
429 const TargetComponent &a = component_list[i];
430 for (size_t j = 0; j < i; j++) {
431 bool target_valid = false;
432 Target new_target;
433 const TargetComponent &b = component_list[j];
434
435 // Reject targets that are too far off vertically.
436 Vector<2> a_center = a.major_axis.Center();
437 if (a_center.y() > b.bottom.y() || a_center.y() < b.top.y()) {
438 continue;
439 }
440 Vector<2> b_center = b.major_axis.Center();
441 if (b_center.y() > a.bottom.y() || b_center.y() < a.top.y()) {
442 continue;
443 }
444
445 if (a.is_right && !b.is_right) {
446 if (a.top.x() > b.top.x()) {
447 new_target.right = a;
448 new_target.left = b;
449 target_valid = true;
450 }
451 } else if (!a.is_right && b.is_right) {
452 if (b.top.x() > a.top.x()) {
453 new_target.right = b;
454 new_target.left = a;
455 target_valid = true;
456 }
457 }
458 if (target_valid) {
459 target_list.emplace_back(new_target);
460 }
461 }
462 }
463 if (verbose) printf("Possible Target: %zu.\n", target_list.size());
464 return target_list;
465}
466
467std::vector<IntermediateResult> TargetFinder::FilterResults(
Ben Fredricksona8c3d552019-03-03 14:14:53 -0800468 const std::vector<IntermediateResult> &results, uint64_t print_rate) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800469 std::vector<IntermediateResult> filtered;
470 for (const IntermediateResult &res : results) {
471 if (res.solver_error < 75.0) {
472 filtered.emplace_back(res);
473 }
474 }
Ben Fredricksona8c3d552019-03-03 14:14:53 -0800475 frame_count_++;
476 if (!filtered.empty()) {
477 valid_result_count_++;
478 }
479 if (print_rate > 0 && frame_count_ > print_rate) {
480 LOG(INFO, "Found (%zu / %zu)(%.2f) targets.\n", valid_result_count_,
481 frame_count_, (double)valid_result_count_ / (double)frame_count_);
482 frame_count_ = 0;
483 valid_result_count_ = 0;
484 }
485
Parker Schuh2a1447c2019-02-17 00:25:29 -0800486 return filtered;
487}
488
489} // namespace vision
490} // namespace y2019