blob: 83d4a01b12ea9fca4c3596c1ff7614a8b29dc71d [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"
Brian Silverman63236772019-03-23 22:02:44 -07004#include "ceres/ceres.h"
Parker Schuh2a1447c2019-02-17 00:25:29 -08005
6using namespace aos::vision;
7
8namespace y2019 {
9namespace vision {
10
Brian Silverman63236772019-03-23 22:02:44 -070011TargetFinder::TargetFinder()
12 : target_template_(Target::MakeTemplate()),
13 ceres_context_(ceres::Context::Create()) {}
14
15TargetFinder::~TargetFinder() {}
Parker Schuh2a1447c2019-02-17 00:25:29 -080016
17aos::vision::RangeImage TargetFinder::Threshold(aos::vision::ImagePtr image) {
18 const uint8_t threshold_value = GetThresholdValue();
Brian Silverman37b15b32019-03-10 13:30:18 -070019 return aos::vision::ThresholdImageWithFunction(
20 image, [&](aos::vision::PixelRef px) {
21 if (px.g > threshold_value && px.b > threshold_value &&
22 px.r > threshold_value) {
23 return true;
24 }
25 return false;
26 });
Parker Schuh2a1447c2019-02-17 00:25:29 -080027}
28
Austin Schuh3b1586a2019-05-02 13:46:52 -070029int TargetFinder::PixelCount(BlobList *imgs) {
30 int num_pixels = 0;
31 for (RangeImage &img : *imgs) {
32 num_pixels += img.npixels();
33 }
34 return num_pixels;
35}
36
Parker Schuh2a1447c2019-02-17 00:25:29 -080037// Filter blobs on size.
38void TargetFinder::PreFilter(BlobList *imgs) {
39 imgs->erase(
40 std::remove_if(imgs->begin(), imgs->end(),
41 [](RangeImage &img) {
42 // We can drop images with a small number of
43 // pixels, but images
44 // must be over 20px or the math will have issues.
45 return (img.npixels() < 100 || img.height() < 25);
46 }),
47 imgs->end());
48}
49
Austin Schuh7d2ef032019-03-10 14:59:34 -070050ContourNode *TargetFinder::GetContour(const RangeImage &blob) {
Ben Fredricksonf7b68522019-03-02 21:19:42 -080051 alloc_.reset();
52 return RangeImgToContour(blob, &alloc_);
53}
54
Ben Fredricksonec575822019-03-02 22:03:20 -080055// TODO(ben): These values will be moved into the constants.h file.
Ben Fredricksonf7b68522019-03-02 21:19:42 -080056namespace {
57
Austin Schuh7d2ef032019-03-10 14:59:34 -070058::Eigen::Vector2f AosVectorToEigenVector(Vector<2> in) {
59 return ::Eigen::Vector2f(in.x(), in.y());
60}
61
Ben Fredricksonec575822019-03-02 22:03:20 -080062constexpr double f_x = 481.4957;
63constexpr double c_x = 341.215;
64constexpr double f_y = 484.314;
65constexpr double c_y = 251.29;
Ben Fredricksonf7b68522019-03-02 21:19:42 -080066
Ben Fredricksonec575822019-03-02 22:03:20 -080067constexpr double f_x_prime = 363.1424;
68constexpr double c_x_prime = 337.9895;
69constexpr double f_y_prime = 366.4837;
70constexpr double c_y_prime = 240.0702;
Ben Fredricksonf7b68522019-03-02 21:19:42 -080071
Ben Fredricksonec575822019-03-02 22:03:20 -080072constexpr double k_1 = -0.2739;
73constexpr double k_2 = 0.01583;
74constexpr double k_3 = 0.04201;
Ben Fredricksonf7b68522019-03-02 21:19:42 -080075
76constexpr int iterations = 7;
77
78}
79
Austin Schuhe5015972019-03-09 17:47:34 -080080::Eigen::Vector2f UnWarpPoint(const Point point) {
Ben Fredricksonec575822019-03-02 22:03:20 -080081 const double x0 = ((double)point.x - c_x) / f_x;
82 const double y0 = ((double)point.y - c_y) / f_y;
Ben Fredricksonf7b68522019-03-02 21:19:42 -080083 double x = x0;
84 double y = y0;
85 for (int i = 0; i < iterations; i++) {
86 const double r_sqr = x * x + y * y;
Alex Perry2ca15742019-03-10 20:38:40 -070087 const double coeff = 1.0 + r_sqr * (k_1 + r_sqr * (k_2 + r_sqr * (k_3)));
Ben Fredricksonf7b68522019-03-02 21:19:42 -080088 x = x0 / coeff;
89 y = y0 / coeff;
90 }
Austin Schuhe5015972019-03-09 17:47:34 -080091 const double nx = x * f_x_prime + c_x_prime;
92 const double ny = y * f_y_prime + c_y_prime;
93 return ::Eigen::Vector2f(nx, ny);
Ben Fredricksonf7b68522019-03-02 21:19:42 -080094}
95
Austin Schuhe5015972019-03-09 17:47:34 -080096::std::vector<::Eigen::Vector2f> TargetFinder::UnWarpContour(
97 ContourNode *start) const {
98 ::std::vector<::Eigen::Vector2f> result;
Ben Fredricksonf7b68522019-03-02 21:19:42 -080099 ContourNode *node = start;
100 while (node->next != start) {
Austin Schuhe5015972019-03-09 17:47:34 -0800101 result.push_back(UnWarpPoint(node->pt));
Ben Fredricksonf7b68522019-03-02 21:19:42 -0800102 node = node->next;
103 }
Austin Schuhe5015972019-03-09 17:47:34 -0800104 result.push_back(UnWarpPoint(node->pt));
105 return result;
Ben Fredricksonf7b68522019-03-02 21:19:42 -0800106}
107
Parker Schuh2a1447c2019-02-17 00:25:29 -0800108// TODO: Try hierarchical merge for this.
109// Convert blobs into polygons.
Austin Schuh6e56faf2019-03-10 14:04:57 -0700110Polygon TargetFinder::FindPolygon(::std::vector<::Eigen::Vector2f> &&contour,
111 bool verbose) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800112 if (verbose) printf("Process Polygon.\n");
Parker Schuh2a1447c2019-02-17 00:25:29 -0800113
Austin Schuhe5015972019-03-09 17:47:34 -0800114 ::std::vector<::Eigen::Vector2f> slopes;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800115
116 // Collect all slopes from the contour.
Austin Schuhe5015972019-03-09 17:47:34 -0800117 ::Eigen::Vector2f previous_point = contour[0];
118 for (size_t i = 0; i < contour.size(); ++i) {
119 ::Eigen::Vector2f next_point = contour[(i + 1) % contour.size()];
Parker Schuh2a1447c2019-02-17 00:25:29 -0800120
Austin Schuhe5015972019-03-09 17:47:34 -0800121 slopes.push_back(next_point - previous_point);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800122
Austin Schuhe5015972019-03-09 17:47:34 -0800123 previous_point = next_point;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800124 }
125
Austin Schuhe5015972019-03-09 17:47:34 -0800126 const int num_points = slopes.size();
127 auto get_pt = [&slopes, num_points](int i) {
128 return slopes[(i + num_points * 2) % num_points];
Austin Schuh335eef12019-03-02 17:04:17 -0800129 };
Parker Schuh2a1447c2019-02-17 00:25:29 -0800130
Austin Schuh6a484962019-03-09 21:51:27 -0800131 // Bigger objects should be more filtered. Filter roughly proportional to the
132 // perimeter of the object.
133 const int range = slopes.size() / 50;
134 if (verbose) printf("Corner range: %d.\n", range);
135
Austin Schuhe5015972019-03-09 17:47:34 -0800136 ::std::vector<::Eigen::Vector2f> filtered_slopes = slopes;
Austin Schuh335eef12019-03-02 17:04:17 -0800137 // Three box filter makith a guassian?
138 // Run gaussian filter over the slopes 3 times. That'll get us pretty close
139 // to running a gausian over it.
140 for (int k = 0; k < 3; ++k) {
Austin Schuh6a484962019-03-09 21:51:27 -0800141 const int window_size = ::std::max(2, range);
Austin Schuhe5015972019-03-09 17:47:34 -0800142 for (size_t i = 0; i < slopes.size(); ++i) {
143 ::Eigen::Vector2f a = ::Eigen::Vector2f::Zero();
Parker Schuh2a1447c2019-02-17 00:25:29 -0800144 for (int j = -window_size; j <= window_size; ++j) {
Austin Schuhe5015972019-03-09 17:47:34 -0800145 ::Eigen::Vector2f p = get_pt(j + i);
146 a += p;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800147 }
Austin Schuhe5015972019-03-09 17:47:34 -0800148 a /= (window_size * 2 + 1);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800149
Austin Schuhe5015972019-03-09 17:47:34 -0800150 filtered_slopes[i] = a;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800151 }
Austin Schuhe5015972019-03-09 17:47:34 -0800152 slopes = filtered_slopes;
Austin Schuh335eef12019-03-02 17:04:17 -0800153 }
Austin Schuh6a484962019-03-09 21:51:27 -0800154 if (verbose) printf("Point count: %zu.\n", slopes.size());
Parker Schuh2a1447c2019-02-17 00:25:29 -0800155
Austin Schuh6a484962019-03-09 21:51:27 -0800156 ::std::vector<float> corner_metric(slopes.size(), 0.0);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800157
Austin Schuh6a484962019-03-09 21:51:27 -0800158 for (size_t i = 0; i < slopes.size(); ++i) {
159 const ::Eigen::Vector2f a = get_pt(i - ::std::max(3, range));
160 const ::Eigen::Vector2f b = get_pt(i + ::std::max(3, range));
161 corner_metric[i] = (a - b).squaredNorm();
162 }
163
164 // We want to find the Nth highest peaks.
165 // Clever algorithm: Find the highest point. Then, walk forwards and
166 // backwards to find the next valley each direction which is over x% lower
167 // than the peak.
168 // We want to ignore those points in the future. Set them to 0.
169 // Repeat until we've found the Nth highest peak.
Parker Schuh2a1447c2019-02-17 00:25:29 -0800170
171 // Find all centers of corners.
Austin Schuhe5015972019-03-09 17:47:34 -0800172 // Because they round, multiple slopes may be a corner.
173 ::std::vector<size_t> edges;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800174
Austin Schuh6a484962019-03-09 21:51:27 -0800175 constexpr float peak_acceptance_ratio = 0.16;
176 constexpr float valley_ratio = 0.75;
177
178 float highest_peak_value = 0.0;
179
180 // Nth higest points.
Austin Schuh32ffac22019-03-09 22:42:02 -0800181 while (edges.size() < 5) {
Austin Schuh6a484962019-03-09 21:51:27 -0800182 const ::std::vector<float>::iterator max_element =
183 ::std::max_element(corner_metric.begin(), corner_metric.end());
184 const size_t highest_index =
185 ::std::distance(corner_metric.begin(), max_element);
186 const float max_value = *max_element;
Austin Schuh32ffac22019-03-09 22:42:02 -0800187 if (edges.size() == 0) {
Austin Schuh6a484962019-03-09 21:51:27 -0800188 highest_peak_value = max_value;
189 }
Austin Schuh32ffac22019-03-09 22:42:02 -0800190 if (max_value < highest_peak_value * peak_acceptance_ratio &&
191 edges.size() == 4) {
Austin Schuh6a484962019-03-09 21:51:27 -0800192 if (verbose)
193 printf("Rejecting index: %zu, %f (%f %%)\n", highest_index, max_value,
194 max_value / highest_peak_value);
195 break;
196 }
197 const float valley_value = max_value * valley_ratio;
198
199 if (verbose)
200 printf("Highest index: %zu, %f (%f %%)\n", highest_index, max_value,
201 max_value / highest_peak_value);
202
Austin Schuh32ffac22019-03-09 22:42:02 -0800203 bool foothill = false;
Austin Schuh6a484962019-03-09 21:51:27 -0800204 {
205 float min_value = max_value;
206 size_t fwd_index = (highest_index + 1) % corner_metric.size();
207 while (true) {
208 const float current_value = corner_metric[fwd_index];
Austin Schuh32ffac22019-03-09 22:42:02 -0800209
210 if (current_value == -1.0) {
211 if (min_value >= valley_value) {
212 if (verbose) printf("Foothill\n");
213 foothill = true;
214 }
215 break;
216 }
217
Austin Schuh6a484962019-03-09 21:51:27 -0800218 min_value = ::std::min(current_value, min_value);
219
Austin Schuh32ffac22019-03-09 22:42:02 -0800220 if (min_value < valley_value && current_value > min_value) {
Austin Schuh6a484962019-03-09 21:51:27 -0800221 break;
222 }
223 // Kill!!!
Austin Schuh32ffac22019-03-09 22:42:02 -0800224 corner_metric[fwd_index] = -1.0;
Austin Schuh6a484962019-03-09 21:51:27 -0800225
226 fwd_index = (fwd_index + 1) % corner_metric.size();
Parker Schuh2a1447c2019-02-17 00:25:29 -0800227 }
228 }
Austin Schuh6a484962019-03-09 21:51:27 -0800229
230 {
231 float min_value = max_value;
232 size_t rev_index =
233 (highest_index - 1 + corner_metric.size()) % corner_metric.size();
234 while (true) {
235 const float current_value = corner_metric[rev_index];
Austin Schuh32ffac22019-03-09 22:42:02 -0800236
237 if (current_value == -1.0) {
238 if (min_value >= valley_value) {
239 if (verbose) printf("Foothill\n");
240 foothill = true;
241 }
242 break;
243 }
244
Austin Schuh6a484962019-03-09 21:51:27 -0800245 min_value = ::std::min(current_value, min_value);
246
Austin Schuh32ffac22019-03-09 22:42:02 -0800247 if (min_value < valley_value && current_value > min_value) {
Austin Schuh6a484962019-03-09 21:51:27 -0800248 break;
249 }
250 // Kill!!!
Austin Schuh32ffac22019-03-09 22:42:02 -0800251 corner_metric[rev_index] = -1.0;
Austin Schuh6a484962019-03-09 21:51:27 -0800252
253 rev_index =
254 (rev_index - 1 + corner_metric.size()) % corner_metric.size();
255 }
Parker Schuh2a1447c2019-02-17 00:25:29 -0800256 }
Austin Schuh6a484962019-03-09 21:51:27 -0800257
Austin Schuh32ffac22019-03-09 22:42:02 -0800258 *max_element = -1.0;
259 if (!foothill) {
260 edges.push_back(highest_index);
261 }
Parker Schuh2a1447c2019-02-17 00:25:29 -0800262 }
263
Austin Schuh6a484962019-03-09 21:51:27 -0800264 ::std::sort(edges.begin(), edges.end());
Parker Schuh2a1447c2019-02-17 00:25:29 -0800265
266 if (verbose) printf("Edge Count (%zu).\n", edges.size());
267
Parker Schuh2a1447c2019-02-17 00:25:29 -0800268 // Run best-fits over each line segment.
Austin Schuh6e56faf2019-03-10 14:04:57 -0700269 Polygon polygon;
Austin Schuh6a484962019-03-09 21:51:27 -0800270 if (edges.size() >= 3) {
Austin Schuhe5015972019-03-09 17:47:34 -0800271 for (size_t i = 0; i < edges.size(); ++i) {
272 // Include the corners in both line fits.
273 const size_t segment_start_index = edges[i];
274 const size_t segment_end_index =
275 (edges[(i + 1) % edges.size()] + 1) % contour.size();
Parker Schuh2a1447c2019-02-17 00:25:29 -0800276 float mx = 0.0;
277 float my = 0.0;
278 int n = 0;
Austin Schuhe5015972019-03-09 17:47:34 -0800279 for (size_t j = segment_start_index; j != segment_end_index;
280 (j = (j + 1) % contour.size())) {
281 mx += contour[j].x();
282 my += contour[j].y();
Parker Schuh2a1447c2019-02-17 00:25:29 -0800283 ++n;
284 // (x - [x] / N) ** 2 = [x * x] - 2 * [x] * [x] / N + [x] * [x] / N / N;
285 }
286 mx /= n;
287 my /= n;
288
289 float xx = 0.0;
290 float xy = 0.0;
291 float yy = 0.0;
Austin Schuhe5015972019-03-09 17:47:34 -0800292 for (size_t j = segment_start_index; j != segment_end_index;
293 (j = (j + 1) % contour.size())) {
294 const float x = contour[j].x() - mx;
295 const float y = contour[j].y() - my;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800296 xx += x * x;
297 xy += x * y;
298 yy += y * y;
299 }
300
301 // TODO: Extract common to hierarchical merge.
Austin Schuh335eef12019-03-02 17:04:17 -0800302 const float neg_b_over_2 = (xx + yy) / 2.0;
303 const float c = (xx * yy - xy * xy);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800304
Austin Schuh335eef12019-03-02 17:04:17 -0800305 const float sqr = sqrt(neg_b_over_2 * neg_b_over_2 - c);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800306
307 {
Austin Schuh335eef12019-03-02 17:04:17 -0800308 const float lam = neg_b_over_2 + sqr;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800309 float x = xy;
310 float y = lam - xx;
311
Austin Schuh335eef12019-03-02 17:04:17 -0800312 const float norm = hypot(x, y);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800313 x /= norm;
314 y /= norm;
315
Austin Schuh6e56faf2019-03-10 14:04:57 -0700316 polygon.segments.push_back(
Parker Schuh2a1447c2019-02-17 00:25:29 -0800317 Segment<2>(Vector<2>(mx, my), Vector<2>(mx + x, my + y)));
318 }
319
320 /* Characteristic polynomial
321 1 lam^2 - (xx + yy) lam + (xx * yy - xy * xy) = 0
322
323 [a b]
324 [c d]
325
326 // covariance matrix.
327 [xx xy] [nx]
328 [xy yy] [ny]
329 */
330 }
331 }
Austin Schuh6e56faf2019-03-10 14:04:57 -0700332 if (verbose) printf("Poly Count (%zu).\n", polygon.segments.size());
333 polygon.contour = ::std::move(contour);
334 return polygon;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800335}
336
337// Convert segments into target components (left or right)
Austin Schuh6e56faf2019-03-10 14:04:57 -0700338::std::vector<TargetComponent> TargetFinder::FillTargetComponentList(
339 const ::std::vector<Polygon> &seg_list, bool verbose) {
340 ::std::vector<TargetComponent> list;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800341 TargetComponent new_target;
Austin Schuh7d2ef032019-03-10 14:59:34 -0700342 for (const Polygon &polygon : seg_list) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800343 // Reject missized pollygons for now. Maybe rectify them here in the future;
Austin Schuh7d2ef032019-03-10 14:59:34 -0700344 if (polygon.segments.size() != 4) {
Austin Schuh9f859ca2019-03-06 20:46:01 -0800345 continue;
346 }
Austin Schuh32ffac22019-03-09 22:42:02 -0800347 ::std::vector<Vector<2>> corners;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800348 for (size_t i = 0; i < 4; ++i) {
Austin Schuh7d2ef032019-03-10 14:59:34 -0700349 Vector<2> corner =
350 polygon.segments[i].Intersect(polygon.segments[(i + 1) % 4]);
Austin Schuh9f859ca2019-03-06 20:46:01 -0800351 if (::std::isnan(corner.x()) || ::std::isnan(corner.y())) {
352 break;
353 }
354 corners.push_back(corner);
355 }
356 if (corners.size() != 4) {
357 continue;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800358 }
359
360 // Select the closest two points. Short side of the rectangle.
361 double min_dist = -1;
Austin Schuh32ffac22019-03-09 22:42:02 -0800362 ::std::pair<size_t, size_t> closest;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800363 for (size_t i = 0; i < 4; ++i) {
364 size_t next = (i + 1) % 4;
365 double nd = corners[i].SquaredDistanceTo(corners[next]);
366 if (min_dist == -1 || nd < min_dist) {
367 min_dist = nd;
368 closest.first = i;
369 closest.second = next;
370 }
371 }
372
373 // Verify our top is above the bottom.
374 size_t bot_index = closest.first;
375 size_t top_index = (closest.first + 2) % 4;
376 if (corners[top_index].y() < corners[bot_index].y()) {
377 closest.first = top_index;
378 closest.second = (top_index + 1) % 4;
379 }
380
381 // Find the major axis.
382 size_t far_first = (closest.first + 2) % 4;
383 size_t far_second = (closest.second + 2) % 4;
384 Segment<2> major_axis(
385 (corners[closest.first] + corners[closest.second]) * 0.5,
386 (corners[far_first] + corners[far_second]) * 0.5);
387 if (major_axis.AsVector().AngleToZero() > M_PI / 180.0 * 120.0 ||
388 major_axis.AsVector().AngleToZero() < M_PI / 180.0 * 60.0) {
389 // Target is angled way too much, drop it.
390 continue;
391 }
392
393 // organize the top points.
394 Vector<2> topA = corners[closest.first] - major_axis.B();
395 new_target.major_axis = major_axis;
396 if (major_axis.AsVector().AngleToZero() > M_PI / 2.0) {
397 // We have a left target since we are leaning positive.
398 new_target.is_right = false;
399 if (topA.AngleTo(major_axis.AsVector()) > 0.0) {
400 // And our A point is left of the major axis.
401 new_target.inside = corners[closest.second];
402 new_target.top = corners[closest.first];
403 } else {
404 // our A point is to the right of the major axis.
405 new_target.inside = corners[closest.first];
406 new_target.top = corners[closest.second];
407 }
408 } else {
409 // We have a right target since we are leaning negative.
410 new_target.is_right = true;
411 if (topA.AngleTo(major_axis.AsVector()) > 0.0) {
412 // And our A point is left of the major axis.
413 new_target.inside = corners[closest.first];
414 new_target.top = corners[closest.second];
415 } else {
416 // our A point is to the right of the major axis.
417 new_target.inside = corners[closest.second];
418 new_target.top = corners[closest.first];
419 }
420 }
421
422 // organize the top points.
423 Vector<2> botA = corners[far_first] - major_axis.A();
424 if (major_axis.AsVector().AngleToZero() > M_PI / 2.0) {
425 // We have a right target since we are leaning positive.
426 if (botA.AngleTo(major_axis.AsVector()) < M_PI) {
427 // And our A point is left of the major axis.
428 new_target.outside = corners[far_second];
429 new_target.bottom = corners[far_first];
430 } else {
431 // our A point is to the right of the major axis.
432 new_target.outside = corners[far_first];
433 new_target.bottom = corners[far_second];
434 }
435 } else {
436 // We have a left target since we are leaning negative.
437 if (botA.AngleTo(major_axis.AsVector()) < M_PI) {
438 // And our A point is left of the major axis.
439 new_target.outside = corners[far_first];
440 new_target.bottom = corners[far_second];
441 } else {
442 // our A point is to the right of the major axis.
443 new_target.outside = corners[far_second];
444 new_target.bottom = corners[far_first];
445 }
446 }
447
Austin Schuh7d2ef032019-03-10 14:59:34 -0700448 // Take the vector which points from the bottom to the top of the target
449 // along the outside edge.
450 const ::Eigen::Vector2f outer_edge_vector =
451 AosVectorToEigenVector(new_target.top - new_target.outside);
452 // Now, dot each point in the perimeter along this vector. The one with the
453 // smallest component will be the one closest to the bottom along this
454 // direction vector.
455 ::Eigen::Vector2f smallest_point = polygon.contour[0];
456 float smallest_value = outer_edge_vector.transpose() * smallest_point;
457 for (const ::Eigen::Vector2f point : polygon.contour) {
458 const float current_value = outer_edge_vector.transpose() * point;
459 if (current_value < smallest_value) {
460 smallest_value = current_value;
461 smallest_point = point;
462 }
463 }
464
465 // This piece of the target should be ready now.
466 new_target.bottom_point = smallest_point;
467 if (verbose) {
468 printf("Lowest point in the blob is (%f, %f)\n", smallest_point.x(),
469 smallest_point.y());
470 }
471
Parker Schuh2a1447c2019-02-17 00:25:29 -0800472 // This piece of the target should be ready now.
473 list.emplace_back(new_target);
Austin Schuh7d2ef032019-03-10 14:59:34 -0700474
Austin Schuh32ffac22019-03-09 22:42:02 -0800475 if (verbose) printf("Happy with a target\n");
Parker Schuh2a1447c2019-02-17 00:25:29 -0800476 }
477
478 return list;
479}
480
481// Match components into targets.
482std::vector<Target> TargetFinder::FindTargetsFromComponents(
483 const std::vector<TargetComponent> component_list, bool verbose) {
484 std::vector<Target> target_list;
485 using namespace aos::vision;
486 if (component_list.size() < 2) {
487 // We don't enough parts for a target.
488 return target_list;
489 }
490
491 for (size_t i = 0; i < component_list.size(); i++) {
492 const TargetComponent &a = component_list[i];
493 for (size_t j = 0; j < i; j++) {
494 bool target_valid = false;
495 Target new_target;
496 const TargetComponent &b = component_list[j];
497
Parker Schuh2a1447c2019-02-17 00:25:29 -0800498 if (a.is_right && !b.is_right) {
499 if (a.top.x() > b.top.x()) {
500 new_target.right = a;
501 new_target.left = b;
502 target_valid = true;
503 }
504 } else if (!a.is_right && b.is_right) {
505 if (b.top.x() > a.top.x()) {
506 new_target.right = b;
507 new_target.left = a;
508 target_valid = true;
509 }
Alex Perrybac3d3f2019-03-10 14:26:51 -0700510 } else if (verbose) {
511 printf("Found same side components: %s.\n",
512 a.is_right ? "right" : "left");
Parker Schuh2a1447c2019-02-17 00:25:29 -0800513 }
514 if (target_valid) {
515 target_list.emplace_back(new_target);
516 }
517 }
518 }
519 if (verbose) printf("Possible Target: %zu.\n", target_list.size());
520 return target_list;
521}
522
Austin Schuhe6cfbe32019-03-10 18:05:57 -0700523bool TargetFinder::MaybePickAndUpdateResult(IntermediateResult *result,
524 bool verbose) {
525 // Based on a linear regression between error and distance to target.
526 // Closer targets can have a higher error because they are bigger.
527 const double acceptable_error =
Alex Perryebc6dd52019-03-16 07:54:48 -0700528 std::max(2 * (75 - 12 * result->extrinsics.z), 75.0);
Austin Schuh45639882019-03-24 19:20:42 -0700529 if (!result->good_corners) {
530 if (verbose) {
531 printf("Rejecting a target with bad corners: (%f, %f)\n",
532 result->solver_error, result->backup_solver_error);
533 }
534 } else if (result->solver_error < acceptable_error) {
Austin Schuhe6cfbe32019-03-10 18:05:57 -0700535 if (verbose) {
536 printf("Using an 8 point solve: %f < %f \n", result->solver_error,
537 acceptable_error);
538 }
539 return true;
540 } else if (result->backup_solver_error < acceptable_error) {
541 if (verbose) {
542 printf("Using a 4 point solve: %f < %f \n", result->backup_solver_error,
543 acceptable_error);
544 }
545 IntermediateResult backup;
546 result->extrinsics = result->backup_extrinsics;
547 result->solver_error = result->backup_solver_error;
548 return true;
549 } else if (verbose) {
550 printf("Rejecting a target with errors: (%f, %f) > %f \n",
551 result->solver_error, result->backup_solver_error, acceptable_error);
552 }
553 return false;
554}
555
Parker Schuh2a1447c2019-02-17 00:25:29 -0800556std::vector<IntermediateResult> TargetFinder::FilterResults(
Alex Perrybac3d3f2019-03-10 14:26:51 -0700557 const std::vector<IntermediateResult> &results, uint64_t print_rate,
558 bool verbose) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800559 std::vector<IntermediateResult> filtered;
560 for (const IntermediateResult &res : results) {
Austin Schuhe6cfbe32019-03-10 18:05:57 -0700561 IntermediateResult updatable_result = res;
562 if (MaybePickAndUpdateResult(&updatable_result, verbose)) {
563 filtered.emplace_back(updatable_result);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800564 }
565 }
Alex Perry5b1e8e32019-04-07 13:25:31 -0700566
567 // Sort the target list so that the widest (ie closest) target is first.
568 sort(filtered.begin(), filtered.end(),
569 [](const IntermediateResult &a, const IntermediateResult &b)
570 -> bool { return a.target_width > b.target_width; });
571
Ben Fredricksona8c3d552019-03-03 14:14:53 -0800572 frame_count_++;
573 if (!filtered.empty()) {
574 valid_result_count_++;
575 }
576 if (print_rate > 0 && frame_count_ > print_rate) {
Brian Silverman63236772019-03-23 22:02:44 -0700577 LOG(INFO) << "Found (" << valid_result_count_ << " / " << frame_count_
578 << ")(" << ((double)valid_result_count_ / (double)frame_count_)
579 << " targets.";
Ben Fredricksona8c3d552019-03-03 14:14:53 -0800580 frame_count_ = 0;
581 valid_result_count_ = 0;
582 }
583
Parker Schuh2a1447c2019-02-17 00:25:29 -0800584 return filtered;
585}
586
Alex Perry5b1e8e32019-04-07 13:25:31 -0700587bool TargetFinder::TestExposure(const std::vector<IntermediateResult> &results,
Austin Schuh3b1586a2019-05-02 13:46:52 -0700588 int pixel_count, int *desired_exposure) {
Alex Perry5b1e8e32019-04-07 13:25:31 -0700589 // TODO(ben): Add these values to config file.
590 constexpr double low_dist = 0.8;
Alex Perry5b1e8e32019-04-07 13:25:31 -0700591 constexpr int low_exposure = 60;
Austin Schuh3b1586a2019-05-02 13:46:52 -0700592 constexpr int mid_exposure = 200;
Alex Perry5b1e8e32019-04-07 13:25:31 -0700593
594 bool needs_update = false;
595 if (results.size() > 0) {
596 // We are seeing a target so lets use an exposure
597 // based on the distance to that target.
598 // First result should always be the closest target.
599 if (results[0].extrinsics.z < low_dist) {
Austin Schuh3b1586a2019-05-02 13:46:52 -0700600 LOG(INFO) << "Low exposure";
Alex Perry5b1e8e32019-04-07 13:25:31 -0700601 *desired_exposure = low_exposure;
Austin Schuh3b1586a2019-05-02 13:46:52 -0700602 close_bucket_ = 4;
Alex Perry5b1e8e32019-04-07 13:25:31 -0700603 } else {
Austin Schuh3b1586a2019-05-02 13:46:52 -0700604 LOG(INFO) << "Mid exposure";
Alex Perry5b1e8e32019-04-07 13:25:31 -0700605 *desired_exposure = mid_exposure;
606 }
607 if (*desired_exposure != current_exposure_) {
608 needs_update = true;
609 current_exposure_ = *desired_exposure;
610 }
611 } else {
Austin Schuh3b1586a2019-05-02 13:46:52 -0700612 close_bucket_ = ::std::max(0, close_bucket_ - 1);
613 // It's been a while since we saw a target.
614 if (close_bucket_ == 0) {
615 if (pixel_count > 6000) {
616 if (low_exposure != current_exposure_) {
617 needs_update = true;
618 current_exposure_ = low_exposure;
619 *desired_exposure = low_exposure;
620 }
621 } else {
622 if (mid_exposure != current_exposure_) {
623 needs_update = true;
624 current_exposure_ = mid_exposure;
625 *desired_exposure = mid_exposure;
626 }
Alex Perry5b1e8e32019-04-07 13:25:31 -0700627 }
628 }
Alex Perry5b1e8e32019-04-07 13:25:31 -0700629 }
630 return needs_update;
631}
632
Parker Schuh2a1447c2019-02-17 00:25:29 -0800633} // namespace vision
634} // namespace y2019