blob: b133bd3be0a0f5cb4bc46dc70a9ea3310c9de194 [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
10TargetFinder::TargetFinder() { target_template_ = Target::MakeTemplate(); }
11
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
41// TODO(ben): These values will be moved into a configuration file.
42namespace {
43
44constexpr double mtx00 = 481.4957;
45constexpr double mtx02 = 341.215;
46constexpr double mtx11 = 484.314;
47constexpr double mtx12 = 251.29;
48
49constexpr double new_cam00 = 363.1424;
50constexpr double new_cam02 = 337.9895;
51constexpr double new_cam11 = 366.4837;
52constexpr double new_cam12 = 240.0702;
53
54constexpr double dist00 = -0.2739;
55constexpr double dist01 = 0.01583;
56constexpr double dist04 = 0.04201;
57
58constexpr int iterations = 7;
59
60}
61
62Point UnWarpPoint(const Point &point, int iterations) {
63 const double x0 = ((double)point.x - mtx02) / mtx00;
64 const double y0 = ((double)point.y - mtx12) / mtx11;
65 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 =
70 1.0 + r_sqr * (dist00 + dist01 * r_sqr * (1.0 + dist04 * r_sqr));
71 x = x0 / coeff;
72 y = y0 / coeff;
73 }
74 double nx = x * new_cam00 + new_cam02;
75 double ny = y * new_cam11 + new_cam12;
76 Point p = {static_cast<int>(nx), static_cast<int>(ny)};
77 return p;
78}
79
80void TargetFinder::UnWarpContour(ContourNode *start) const {
81 ContourNode *node = start;
82 while (node->next != start) {
83 node->set_point(UnWarpPoint(node->pt, iterations));
84 node = node->next;
85 }
86 node->set_point(UnWarpPoint(node->pt, iterations));
87}
88
Parker Schuh2a1447c2019-02-17 00:25:29 -080089// TODO: Try hierarchical merge for this.
90// Convert blobs into polygons.
91std::vector<aos::vision::Segment<2>> TargetFinder::FillPolygon(
Ben Fredricksonf7b68522019-03-02 21:19:42 -080092 ContourNode* start, bool verbose) {
Parker Schuh2a1447c2019-02-17 00:25:29 -080093 if (verbose) printf("Process Polygon.\n");
Parker Schuh2a1447c2019-02-17 00:25:29 -080094
95 struct Pt {
96 float x;
97 float y;
98 };
Austin Schuh335eef12019-03-02 17:04:17 -080099 std::vector<Pt> points;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800100
101 // Collect all slopes from the contour.
Austin Schuh335eef12019-03-02 17:04:17 -0800102 Point previous_point = start->pt;
103 for (ContourNode *node = start; node->next != start;) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800104 node = node->next;
105
Austin Schuh335eef12019-03-02 17:04:17 -0800106 Point current_point = node->pt;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800107
Austin Schuh335eef12019-03-02 17:04:17 -0800108 points.push_back({static_cast<float>(current_point.x - previous_point.x),
109 static_cast<float>(current_point.y - previous_point.y)});
Parker Schuh2a1447c2019-02-17 00:25:29 -0800110
Austin Schuh335eef12019-03-02 17:04:17 -0800111 previous_point = current_point;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800112 }
113
Austin Schuh335eef12019-03-02 17:04:17 -0800114 const int num_points = points.size();
115 auto get_pt = [&points, num_points](int i) {
116 return points[(i + num_points * 2) % num_points];
117 };
Parker Schuh2a1447c2019-02-17 00:25:29 -0800118
Austin Schuh335eef12019-03-02 17:04:17 -0800119 std::vector<Pt> filtered_points = points;
120 // 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) {
124 const int window_size = 2;
125 for (size_t i = 0; i < points.size(); ++i) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800126 Pt a{0.0, 0.0};
127 for (int j = -window_size; j <= window_size; ++j) {
128 Pt p = get_pt(j + i);
129 a.x += p.x;
130 a.y += p.y;
131 }
132 a.x /= (window_size * 2 + 1);
133 a.y /= (window_size * 2 + 1);
134
Austin Schuh335eef12019-03-02 17:04:17 -0800135 const float scale = 1.0 + (i / float(points.size() * 10));
Parker Schuh2a1447c2019-02-17 00:25:29 -0800136 a.x *= scale;
137 a.y *= scale;
Austin Schuh335eef12019-03-02 17:04:17 -0800138 filtered_points[i] = a;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800139 }
Austin Schuh335eef12019-03-02 17:04:17 -0800140 points = filtered_points;
141 }
Parker Schuh2a1447c2019-02-17 00:25:29 -0800142
143 // Heuristic which says if a particular slope is part of a corner.
144 auto is_corner = [&](size_t i) {
Austin Schuh335eef12019-03-02 17:04:17 -0800145 const Pt a = get_pt(i - 3);
146 const Pt b = get_pt(i + 3);
147 const double dx = (a.x - b.x);
148 const double dy = (a.y - b.y);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800149 return dx * dx + dy * dy > 0.25;
150 };
151
152 bool prev_v = is_corner(-1);
153
154 // Find all centers of corners.
155 // Because they round, multiple points may be a corner.
156 std::vector<size_t> edges;
Austin Schuh335eef12019-03-02 17:04:17 -0800157 size_t kBad = points.size() + 10;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800158 size_t prev_up = kBad;
159 size_t wrapped_n = prev_up;
160
Austin Schuh335eef12019-03-02 17:04:17 -0800161 for (size_t i = 0; i < points.size(); ++i) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800162 bool v = is_corner(i);
163 if (prev_v && !v) {
164 if (prev_up == kBad) {
165 wrapped_n = i;
166 } else {
167 edges.push_back((prev_up + i - 1) / 2);
168 }
169 }
170 if (v && !prev_v) {
171 prev_up = i;
172 }
173 prev_v = v;
174 }
175
176 if (wrapped_n != kBad) {
Austin Schuh335eef12019-03-02 17:04:17 -0800177 edges.push_back(((prev_up + points.size() + wrapped_n - 1) / 2) % points.size());
Parker Schuh2a1447c2019-02-17 00:25:29 -0800178 }
179
180 if (verbose) printf("Edge Count (%zu).\n", edges.size());
181
182 // Get all CountourNodes from the contour.
183 using aos::vision::PixelRef;
184 std::vector<ContourNode *> segments;
185 {
186 std::vector<ContourNode *> segments_all;
187
Austin Schuh335eef12019-03-02 17:04:17 -0800188 for (ContourNode *node = start; node->next != start;) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800189 node = node->next;
190 segments_all.push_back(node);
191 }
192 for (size_t i : edges) {
193 segments.push_back(segments_all[i]);
194 }
195 }
196 if (verbose) printf("Segment Count (%zu).\n", segments.size());
197
198 // Run best-fits over each line segment.
199 std::vector<Segment<2>> seg_list;
200 if (segments.size() == 4) {
201 for (size_t i = 0; i < segments.size(); ++i) {
Austin Schuh335eef12019-03-02 17:04:17 -0800202 ContourNode *segment_end = segments[(i + 1) % segments.size()];
203 ContourNode *segment_start = segments[i];
Parker Schuh2a1447c2019-02-17 00:25:29 -0800204 float mx = 0.0;
205 float my = 0.0;
206 int n = 0;
Austin Schuh335eef12019-03-02 17:04:17 -0800207 for (ContourNode *node = segment_start; node != segment_end;
208 node = node->next) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800209 mx += node->pt.x;
210 my += node->pt.y;
211 ++n;
212 // (x - [x] / N) ** 2 = [x * x] - 2 * [x] * [x] / N + [x] * [x] / N / N;
213 }
214 mx /= n;
215 my /= n;
216
217 float xx = 0.0;
218 float xy = 0.0;
219 float yy = 0.0;
Austin Schuh335eef12019-03-02 17:04:17 -0800220 for (ContourNode *node = segment_start; node != segment_end;
221 node = node->next) {
222 const float x = node->pt.x - mx;
223 const float y = node->pt.y - my;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800224 xx += x * x;
225 xy += x * y;
226 yy += y * y;
227 }
228
229 // TODO: Extract common to hierarchical merge.
Austin Schuh335eef12019-03-02 17:04:17 -0800230 const float neg_b_over_2 = (xx + yy) / 2.0;
231 const float c = (xx * yy - xy * xy);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800232
Austin Schuh335eef12019-03-02 17:04:17 -0800233 const float sqr = sqrt(neg_b_over_2 * neg_b_over_2 - c);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800234
235 {
Austin Schuh335eef12019-03-02 17:04:17 -0800236 const float lam = neg_b_over_2 + sqr;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800237 float x = xy;
238 float y = lam - xx;
239
Austin Schuh335eef12019-03-02 17:04:17 -0800240 const float norm = hypot(x, y);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800241 x /= norm;
242 y /= norm;
243
244 seg_list.push_back(
245 Segment<2>(Vector<2>(mx, my), Vector<2>(mx + x, my + y)));
246 }
247
248 /* Characteristic polynomial
249 1 lam^2 - (xx + yy) lam + (xx * yy - xy * xy) = 0
250
251 [a b]
252 [c d]
253
254 // covariance matrix.
255 [xx xy] [nx]
256 [xy yy] [ny]
257 */
258 }
259 }
260 if (verbose) printf("Poly Count (%zu).\n", seg_list.size());
261 return seg_list;
262}
263
264// Convert segments into target components (left or right)
265std::vector<TargetComponent> TargetFinder::FillTargetComponentList(
266 const std::vector<std::vector<Segment<2>>> &seg_list) {
267 std::vector<TargetComponent> list;
268 TargetComponent new_target;
Austin Schuh335eef12019-03-02 17:04:17 -0800269 for (const std::vector<Segment<2>> &poly : seg_list) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800270 // Reject missized pollygons for now. Maybe rectify them here in the future;
271 if (poly.size() != 4) continue;
272 std::vector<Vector<2>> corners;
273 for (size_t i = 0; i < 4; ++i) {
274 corners.push_back(poly[i].Intersect(poly[(i + 1) % 4]));
275 }
276
277 // Select the closest two points. Short side of the rectangle.
278 double min_dist = -1;
279 std::pair<size_t, size_t> closest;
280 for (size_t i = 0; i < 4; ++i) {
281 size_t next = (i + 1) % 4;
282 double nd = corners[i].SquaredDistanceTo(corners[next]);
283 if (min_dist == -1 || nd < min_dist) {
284 min_dist = nd;
285 closest.first = i;
286 closest.second = next;
287 }
288 }
289
290 // Verify our top is above the bottom.
291 size_t bot_index = closest.first;
292 size_t top_index = (closest.first + 2) % 4;
293 if (corners[top_index].y() < corners[bot_index].y()) {
294 closest.first = top_index;
295 closest.second = (top_index + 1) % 4;
296 }
297
298 // Find the major axis.
299 size_t far_first = (closest.first + 2) % 4;
300 size_t far_second = (closest.second + 2) % 4;
301 Segment<2> major_axis(
302 (corners[closest.first] + corners[closest.second]) * 0.5,
303 (corners[far_first] + corners[far_second]) * 0.5);
304 if (major_axis.AsVector().AngleToZero() > M_PI / 180.0 * 120.0 ||
305 major_axis.AsVector().AngleToZero() < M_PI / 180.0 * 60.0) {
306 // Target is angled way too much, drop it.
307 continue;
308 }
309
310 // organize the top points.
311 Vector<2> topA = corners[closest.first] - major_axis.B();
312 new_target.major_axis = major_axis;
313 if (major_axis.AsVector().AngleToZero() > M_PI / 2.0) {
314 // We have a left target since we are leaning positive.
315 new_target.is_right = false;
316 if (topA.AngleTo(major_axis.AsVector()) > 0.0) {
317 // And our A point is left of the major axis.
318 new_target.inside = corners[closest.second];
319 new_target.top = corners[closest.first];
320 } else {
321 // our A point is to the right of the major axis.
322 new_target.inside = corners[closest.first];
323 new_target.top = corners[closest.second];
324 }
325 } else {
326 // We have a right target since we are leaning negative.
327 new_target.is_right = true;
328 if (topA.AngleTo(major_axis.AsVector()) > 0.0) {
329 // And our A point is left of the major axis.
330 new_target.inside = corners[closest.first];
331 new_target.top = corners[closest.second];
332 } else {
333 // our A point is to the right of the major axis.
334 new_target.inside = corners[closest.second];
335 new_target.top = corners[closest.first];
336 }
337 }
338
339 // organize the top points.
340 Vector<2> botA = corners[far_first] - major_axis.A();
341 if (major_axis.AsVector().AngleToZero() > M_PI / 2.0) {
342 // We have a right target since we are leaning positive.
343 if (botA.AngleTo(major_axis.AsVector()) < M_PI) {
344 // And our A point is left of the major axis.
345 new_target.outside = corners[far_second];
346 new_target.bottom = corners[far_first];
347 } else {
348 // our A point is to the right of the major axis.
349 new_target.outside = corners[far_first];
350 new_target.bottom = corners[far_second];
351 }
352 } else {
353 // We have a left target since we are leaning negative.
354 if (botA.AngleTo(major_axis.AsVector()) < M_PI) {
355 // And our A point is left of the major axis.
356 new_target.outside = corners[far_first];
357 new_target.bottom = corners[far_second];
358 } else {
359 // our A point is to the right of the major axis.
360 new_target.outside = corners[far_second];
361 new_target.bottom = corners[far_first];
362 }
363 }
364
365 // This piece of the target should be ready now.
366 list.emplace_back(new_target);
367 }
368
369 return list;
370}
371
372// Match components into targets.
373std::vector<Target> TargetFinder::FindTargetsFromComponents(
374 const std::vector<TargetComponent> component_list, bool verbose) {
375 std::vector<Target> target_list;
376 using namespace aos::vision;
377 if (component_list.size() < 2) {
378 // We don't enough parts for a target.
379 return target_list;
380 }
381
382 for (size_t i = 0; i < component_list.size(); i++) {
383 const TargetComponent &a = component_list[i];
384 for (size_t j = 0; j < i; j++) {
385 bool target_valid = false;
386 Target new_target;
387 const TargetComponent &b = component_list[j];
388
389 // Reject targets that are too far off vertically.
390 Vector<2> a_center = a.major_axis.Center();
391 if (a_center.y() > b.bottom.y() || a_center.y() < b.top.y()) {
392 continue;
393 }
394 Vector<2> b_center = b.major_axis.Center();
395 if (b_center.y() > a.bottom.y() || b_center.y() < a.top.y()) {
396 continue;
397 }
398
399 if (a.is_right && !b.is_right) {
400 if (a.top.x() > b.top.x()) {
401 new_target.right = a;
402 new_target.left = b;
403 target_valid = true;
404 }
405 } else if (!a.is_right && b.is_right) {
406 if (b.top.x() > a.top.x()) {
407 new_target.right = b;
408 new_target.left = a;
409 target_valid = true;
410 }
411 }
412 if (target_valid) {
413 target_list.emplace_back(new_target);
414 }
415 }
416 }
417 if (verbose) printf("Possible Target: %zu.\n", target_list.size());
418 return target_list;
419}
420
421std::vector<IntermediateResult> TargetFinder::FilterResults(
422 const std::vector<IntermediateResult> &results) {
423 std::vector<IntermediateResult> filtered;
424 for (const IntermediateResult &res : results) {
425 if (res.solver_error < 75.0) {
426 filtered.emplace_back(res);
427 }
428 }
429 return filtered;
430}
431
432} // namespace vision
433} // namespace y2019