| 33 | } |
| 34 | |
| 35 | static void optical_flow_demo(bool console) { |
| 36 | af::Window wnd("Horn-Schunck Optical Flow Demo"); |
| 37 | wnd.setColorMap(AF_COLORMAP_COLORS); |
| 38 | |
| 39 | double time_total = 10; // run for N seconds |
| 40 | |
| 41 | const float h_mean_kernel[] = {1.0f / 12.0f, 2.0f / 12.0f, 1.0f / 12.0f, |
| 42 | 2.0f / 12.0f, 0.0f, 2.0f / 12.0f, |
| 43 | 1.0f / 12.0f, 2.0f / 12.0f, 1.1f / 12.0f}; |
| 44 | array mean_kernel = array(dim4(3, 3), h_mean_kernel, afHost); |
| 45 | |
| 46 | array I1 = |
| 47 | loadImage(ASSETS_DIR "/examples/images/circle_left.ppm"); // grayscale |
| 48 | array I2 = loadImage(ASSETS_DIR "/examples/images/circle_center.ppm"); |
| 49 | |
| 50 | array u = constant(0, I1.dims()), v = constant(0, I1.dims()); |
| 51 | array Ix, Iy, It; |
| 52 | diffs(Ix, Iy, It, I1, I2); |
| 53 | |
| 54 | timer time_start, time_last; |
| 55 | time_start = time_last = timer::start(); |
| 56 | int iter = 0, iter_last = 0; |
| 57 | double max_rate = 0; |
| 58 | |
| 59 | while (true) { |
| 60 | iter++; |
| 61 | array u_ = convolve(u, mean_kernel); |
| 62 | array v_ = convolve(v, mean_kernel); |
| 63 | |
| 64 | const float alphasq = 0.1f; |
| 65 | array num = Ix * u_ + Iy * v_ + It; |
| 66 | array den = alphasq + Ix * Ix + Iy * Iy; |
| 67 | |
| 68 | array tmp = 0.01 * num; |
| 69 | u = u_ - (Ix * tmp) / den; |
| 70 | v = v_ - (Iy * tmp) / den; |
| 71 | |
| 72 | if (!console) { |
| 73 | wnd.grid(2, 2); |
| 74 | |
| 75 | wnd(0, 0).image(I1, "I1"); |
| 76 | wnd(1, 0).image(I2, "I2"); |
| 77 | wnd(0, 1).image(u, "u"); |
| 78 | wnd(1, 1).image(v, "v"); |
| 79 | |
| 80 | wnd.show(); |
| 81 | } |
| 82 | |
| 83 | double elapsed = timer::stop(time_last); |
| 84 | if (elapsed > 1) { |
| 85 | double rate = (iter - iter_last) / elapsed; |
| 86 | double total_elapsed = timer::stop(time_start); |
| 87 | time_last = timer::start(); |
| 88 | iter_last = iter; |
| 89 | max_rate = std::max(max_rate, rate); |
| 90 | if (total_elapsed >= time_total) { break; } |
| 91 | if (!console) |
| 92 | printf(" iterations per second: %.0f (progress %.0f%%)\n", |
no test coverage detected