blob: 6b9008019f24bc2daee5300383a246dfd24dbfb1 [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
36// TODO: Try hierarchical merge for this.
37// Convert blobs into polygons.
38std::vector<aos::vision::Segment<2>> TargetFinder::FillPolygon(
39 const RangeImage &blob, bool verbose) {
40 if (verbose) printf("Process Polygon.\n");
41 alloc_.reset();
Austin Schuh335eef12019-03-02 17:04:17 -080042 ContourNode *start = RangeImgToContour(blob, &alloc_);
Parker Schuh2a1447c2019-02-17 00:25:29 -080043
44 struct Pt {
45 float x;
46 float y;
47 };
Austin Schuh335eef12019-03-02 17:04:17 -080048 std::vector<Pt> points;
Parker Schuh2a1447c2019-02-17 00:25:29 -080049
50 // Collect all slopes from the contour.
Austin Schuh335eef12019-03-02 17:04:17 -080051 Point previous_point = start->pt;
52 for (ContourNode *node = start; node->next != start;) {
Parker Schuh2a1447c2019-02-17 00:25:29 -080053 node = node->next;
54
Austin Schuh335eef12019-03-02 17:04:17 -080055 Point current_point = node->pt;
Parker Schuh2a1447c2019-02-17 00:25:29 -080056
Austin Schuh335eef12019-03-02 17:04:17 -080057 points.push_back({static_cast<float>(current_point.x - previous_point.x),
58 static_cast<float>(current_point.y - previous_point.y)});
Parker Schuh2a1447c2019-02-17 00:25:29 -080059
Austin Schuh335eef12019-03-02 17:04:17 -080060 previous_point = current_point;
Parker Schuh2a1447c2019-02-17 00:25:29 -080061 }
62
Austin Schuh335eef12019-03-02 17:04:17 -080063 const int num_points = points.size();
64 auto get_pt = [&points, num_points](int i) {
65 return points[(i + num_points * 2) % num_points];
66 };
Parker Schuh2a1447c2019-02-17 00:25:29 -080067
Austin Schuh335eef12019-03-02 17:04:17 -080068 std::vector<Pt> filtered_points = points;
69 // Three box filter makith a guassian?
70 // Run gaussian filter over the slopes 3 times. That'll get us pretty close
71 // to running a gausian over it.
72 for (int k = 0; k < 3; ++k) {
73 const int window_size = 2;
74 for (size_t i = 0; i < points.size(); ++i) {
Parker Schuh2a1447c2019-02-17 00:25:29 -080075 Pt a{0.0, 0.0};
76 for (int j = -window_size; j <= window_size; ++j) {
77 Pt p = get_pt(j + i);
78 a.x += p.x;
79 a.y += p.y;
80 }
81 a.x /= (window_size * 2 + 1);
82 a.y /= (window_size * 2 + 1);
83
Austin Schuh335eef12019-03-02 17:04:17 -080084 const float scale = 1.0 + (i / float(points.size() * 10));
Parker Schuh2a1447c2019-02-17 00:25:29 -080085 a.x *= scale;
86 a.y *= scale;
Austin Schuh335eef12019-03-02 17:04:17 -080087 filtered_points[i] = a;
Parker Schuh2a1447c2019-02-17 00:25:29 -080088 }
Austin Schuh335eef12019-03-02 17:04:17 -080089 points = filtered_points;
90 }
Parker Schuh2a1447c2019-02-17 00:25:29 -080091
92 // Heuristic which says if a particular slope is part of a corner.
93 auto is_corner = [&](size_t i) {
Austin Schuh335eef12019-03-02 17:04:17 -080094 const Pt a = get_pt(i - 3);
95 const Pt b = get_pt(i + 3);
96 const double dx = (a.x - b.x);
97 const double dy = (a.y - b.y);
Parker Schuh2a1447c2019-02-17 00:25:29 -080098 return dx * dx + dy * dy > 0.25;
99 };
100
101 bool prev_v = is_corner(-1);
102
103 // Find all centers of corners.
104 // Because they round, multiple points may be a corner.
105 std::vector<size_t> edges;
Austin Schuh335eef12019-03-02 17:04:17 -0800106 size_t kBad = points.size() + 10;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800107 size_t prev_up = kBad;
108 size_t wrapped_n = prev_up;
109
Austin Schuh335eef12019-03-02 17:04:17 -0800110 for (size_t i = 0; i < points.size(); ++i) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800111 bool v = is_corner(i);
112 if (prev_v && !v) {
113 if (prev_up == kBad) {
114 wrapped_n = i;
115 } else {
116 edges.push_back((prev_up + i - 1) / 2);
117 }
118 }
119 if (v && !prev_v) {
120 prev_up = i;
121 }
122 prev_v = v;
123 }
124
125 if (wrapped_n != kBad) {
Austin Schuh335eef12019-03-02 17:04:17 -0800126 edges.push_back(((prev_up + points.size() + wrapped_n - 1) / 2) % points.size());
Parker Schuh2a1447c2019-02-17 00:25:29 -0800127 }
128
129 if (verbose) printf("Edge Count (%zu).\n", edges.size());
130
131 // Get all CountourNodes from the contour.
132 using aos::vision::PixelRef;
133 std::vector<ContourNode *> segments;
134 {
135 std::vector<ContourNode *> segments_all;
136
Austin Schuh335eef12019-03-02 17:04:17 -0800137 for (ContourNode *node = start; node->next != start;) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800138 node = node->next;
139 segments_all.push_back(node);
140 }
141 for (size_t i : edges) {
142 segments.push_back(segments_all[i]);
143 }
144 }
145 if (verbose) printf("Segment Count (%zu).\n", segments.size());
146
147 // Run best-fits over each line segment.
148 std::vector<Segment<2>> seg_list;
149 if (segments.size() == 4) {
150 for (size_t i = 0; i < segments.size(); ++i) {
Austin Schuh335eef12019-03-02 17:04:17 -0800151 ContourNode *segment_end = segments[(i + 1) % segments.size()];
152 ContourNode *segment_start = segments[i];
Parker Schuh2a1447c2019-02-17 00:25:29 -0800153 float mx = 0.0;
154 float my = 0.0;
155 int n = 0;
Austin Schuh335eef12019-03-02 17:04:17 -0800156 for (ContourNode *node = segment_start; node != segment_end;
157 node = node->next) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800158 mx += node->pt.x;
159 my += node->pt.y;
160 ++n;
161 // (x - [x] / N) ** 2 = [x * x] - 2 * [x] * [x] / N + [x] * [x] / N / N;
162 }
163 mx /= n;
164 my /= n;
165
166 float xx = 0.0;
167 float xy = 0.0;
168 float yy = 0.0;
Austin Schuh335eef12019-03-02 17:04:17 -0800169 for (ContourNode *node = segment_start; node != segment_end;
170 node = node->next) {
171 const float x = node->pt.x - mx;
172 const float y = node->pt.y - my;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800173 xx += x * x;
174 xy += x * y;
175 yy += y * y;
176 }
177
178 // TODO: Extract common to hierarchical merge.
Austin Schuh335eef12019-03-02 17:04:17 -0800179 const float neg_b_over_2 = (xx + yy) / 2.0;
180 const float c = (xx * yy - xy * xy);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800181
Austin Schuh335eef12019-03-02 17:04:17 -0800182 const float sqr = sqrt(neg_b_over_2 * neg_b_over_2 - c);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800183
184 {
Austin Schuh335eef12019-03-02 17:04:17 -0800185 const float lam = neg_b_over_2 + sqr;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800186 float x = xy;
187 float y = lam - xx;
188
Austin Schuh335eef12019-03-02 17:04:17 -0800189 const float norm = hypot(x, y);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800190 x /= norm;
191 y /= norm;
192
193 seg_list.push_back(
194 Segment<2>(Vector<2>(mx, my), Vector<2>(mx + x, my + y)));
195 }
196
197 /* Characteristic polynomial
198 1 lam^2 - (xx + yy) lam + (xx * yy - xy * xy) = 0
199
200 [a b]
201 [c d]
202
203 // covariance matrix.
204 [xx xy] [nx]
205 [xy yy] [ny]
206 */
207 }
208 }
209 if (verbose) printf("Poly Count (%zu).\n", seg_list.size());
210 return seg_list;
211}
212
213// Convert segments into target components (left or right)
214std::vector<TargetComponent> TargetFinder::FillTargetComponentList(
215 const std::vector<std::vector<Segment<2>>> &seg_list) {
216 std::vector<TargetComponent> list;
217 TargetComponent new_target;
Austin Schuh335eef12019-03-02 17:04:17 -0800218 for (const std::vector<Segment<2>> &poly : seg_list) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800219 // Reject missized pollygons for now. Maybe rectify them here in the future;
220 if (poly.size() != 4) continue;
221 std::vector<Vector<2>> corners;
222 for (size_t i = 0; i < 4; ++i) {
223 corners.push_back(poly[i].Intersect(poly[(i + 1) % 4]));
224 }
225
226 // Select the closest two points. Short side of the rectangle.
227 double min_dist = -1;
228 std::pair<size_t, size_t> closest;
229 for (size_t i = 0; i < 4; ++i) {
230 size_t next = (i + 1) % 4;
231 double nd = corners[i].SquaredDistanceTo(corners[next]);
232 if (min_dist == -1 || nd < min_dist) {
233 min_dist = nd;
234 closest.first = i;
235 closest.second = next;
236 }
237 }
238
239 // Verify our top is above the bottom.
240 size_t bot_index = closest.first;
241 size_t top_index = (closest.first + 2) % 4;
242 if (corners[top_index].y() < corners[bot_index].y()) {
243 closest.first = top_index;
244 closest.second = (top_index + 1) % 4;
245 }
246
247 // Find the major axis.
248 size_t far_first = (closest.first + 2) % 4;
249 size_t far_second = (closest.second + 2) % 4;
250 Segment<2> major_axis(
251 (corners[closest.first] + corners[closest.second]) * 0.5,
252 (corners[far_first] + corners[far_second]) * 0.5);
253 if (major_axis.AsVector().AngleToZero() > M_PI / 180.0 * 120.0 ||
254 major_axis.AsVector().AngleToZero() < M_PI / 180.0 * 60.0) {
255 // Target is angled way too much, drop it.
256 continue;
257 }
258
259 // organize the top points.
260 Vector<2> topA = corners[closest.first] - major_axis.B();
261 new_target.major_axis = major_axis;
262 if (major_axis.AsVector().AngleToZero() > M_PI / 2.0) {
263 // We have a left target since we are leaning positive.
264 new_target.is_right = false;
265 if (topA.AngleTo(major_axis.AsVector()) > 0.0) {
266 // And our A point is left of the major axis.
267 new_target.inside = corners[closest.second];
268 new_target.top = corners[closest.first];
269 } else {
270 // our A point is to the right of the major axis.
271 new_target.inside = corners[closest.first];
272 new_target.top = corners[closest.second];
273 }
274 } else {
275 // We have a right target since we are leaning negative.
276 new_target.is_right = true;
277 if (topA.AngleTo(major_axis.AsVector()) > 0.0) {
278 // And our A point is left of the major axis.
279 new_target.inside = corners[closest.first];
280 new_target.top = corners[closest.second];
281 } else {
282 // our A point is to the right of the major axis.
283 new_target.inside = corners[closest.second];
284 new_target.top = corners[closest.first];
285 }
286 }
287
288 // organize the top points.
289 Vector<2> botA = corners[far_first] - major_axis.A();
290 if (major_axis.AsVector().AngleToZero() > M_PI / 2.0) {
291 // We have a right target since we are leaning positive.
292 if (botA.AngleTo(major_axis.AsVector()) < M_PI) {
293 // And our A point is left of the major axis.
294 new_target.outside = corners[far_second];
295 new_target.bottom = corners[far_first];
296 } else {
297 // our A point is to the right of the major axis.
298 new_target.outside = corners[far_first];
299 new_target.bottom = corners[far_second];
300 }
301 } else {
302 // We have a left target since we are leaning negative.
303 if (botA.AngleTo(major_axis.AsVector()) < M_PI) {
304 // And our A point is left of the major axis.
305 new_target.outside = corners[far_first];
306 new_target.bottom = corners[far_second];
307 } else {
308 // our A point is to the right of the major axis.
309 new_target.outside = corners[far_second];
310 new_target.bottom = corners[far_first];
311 }
312 }
313
314 // This piece of the target should be ready now.
315 list.emplace_back(new_target);
316 }
317
318 return list;
319}
320
321// Match components into targets.
322std::vector<Target> TargetFinder::FindTargetsFromComponents(
323 const std::vector<TargetComponent> component_list, bool verbose) {
324 std::vector<Target> target_list;
325 using namespace aos::vision;
326 if (component_list.size() < 2) {
327 // We don't enough parts for a target.
328 return target_list;
329 }
330
331 for (size_t i = 0; i < component_list.size(); i++) {
332 const TargetComponent &a = component_list[i];
333 for (size_t j = 0; j < i; j++) {
334 bool target_valid = false;
335 Target new_target;
336 const TargetComponent &b = component_list[j];
337
338 // Reject targets that are too far off vertically.
339 Vector<2> a_center = a.major_axis.Center();
340 if (a_center.y() > b.bottom.y() || a_center.y() < b.top.y()) {
341 continue;
342 }
343 Vector<2> b_center = b.major_axis.Center();
344 if (b_center.y() > a.bottom.y() || b_center.y() < a.top.y()) {
345 continue;
346 }
347
348 if (a.is_right && !b.is_right) {
349 if (a.top.x() > b.top.x()) {
350 new_target.right = a;
351 new_target.left = b;
352 target_valid = true;
353 }
354 } else if (!a.is_right && b.is_right) {
355 if (b.top.x() > a.top.x()) {
356 new_target.right = b;
357 new_target.left = a;
358 target_valid = true;
359 }
360 }
361 if (target_valid) {
362 target_list.emplace_back(new_target);
363 }
364 }
365 }
366 if (verbose) printf("Possible Target: %zu.\n", target_list.size());
367 return target_list;
368}
369
370std::vector<IntermediateResult> TargetFinder::FilterResults(
371 const std::vector<IntermediateResult> &results) {
372 std::vector<IntermediateResult> filtered;
373 for (const IntermediateResult &res : results) {
374 if (res.solver_error < 75.0) {
375 filtered.emplace_back(res);
376 }
377 }
378 return filtered;
379}
380
381} // namespace vision
382} // namespace y2019