|
| 1 | +#include <iostream> |
| 2 | +#include <opencv2/core.hpp> |
| 3 | +#include <opencv2/highgui.hpp> |
| 4 | +#include <opencv2/imgproc.hpp> |
| 5 | +#include <opencv2/videoio.hpp> |
| 6 | + |
| 7 | + |
| 8 | +using namespace cv; |
| 9 | +using namespace std; |
| 10 | + |
| 11 | +template <typename Method, typename... Args> |
| 12 | +void dense_optical_flow(string filename, bool save, Method method, bool to_gray, Args&&... args) |
| 13 | +{ |
| 14 | + VideoCapture capture(samples::findFile(filename)); |
| 15 | + if (!capture.isOpened()) { |
| 16 | + //error in opening the video input |
| 17 | + cerr << "Unable to open file!" << endl; |
| 18 | + } |
| 19 | + Mat frame1, prvs; |
| 20 | + capture >> frame1; |
| 21 | + if (to_gray) |
| 22 | + cvtColor(frame1, prvs, COLOR_BGR2GRAY); |
| 23 | + else |
| 24 | + prvs = frame1; |
| 25 | + int counter = 0; |
| 26 | + while (true) { |
| 27 | + Mat frame2, next; |
| 28 | + capture >> frame2; |
| 29 | + if (frame2.empty()) |
| 30 | + break; |
| 31 | + if (to_gray) |
| 32 | + cvtColor(frame2, next, COLOR_BGR2GRAY); |
| 33 | + else |
| 34 | + next = frame2; |
| 35 | + Mat flow(prvs.size(), CV_32FC2); |
| 36 | + method(prvs, next, flow, std::forward<Args>(args)...); |
| 37 | + // visualization |
| 38 | + Mat flow_parts[2]; |
| 39 | + split(flow, flow_parts); |
| 40 | + Mat magnitude, angle, magn_norm; |
| 41 | + cartToPolar(flow_parts[0], flow_parts[1], magnitude, angle, true); |
| 42 | + normalize(magnitude, magn_norm, 0.0f, 1.0f, NORM_MINMAX); |
| 43 | + angle *= ((1.f / 360.f) * (180.f / 255.f)); |
| 44 | + //build hsv image |
| 45 | + Mat _hsv[3], hsv, hsv8, bgr; |
| 46 | + _hsv[0] = angle; |
| 47 | + _hsv[1] = Mat::ones(angle.size(), CV_32F); |
| 48 | + _hsv[2] = magn_norm; |
| 49 | + merge(_hsv, 3, hsv); |
| 50 | + hsv.convertTo(hsv8, CV_8U, 255.0); |
| 51 | + cvtColor(hsv8, bgr, COLOR_HSV2BGR); |
| 52 | + if (save) { |
| 53 | + string save_path = "./optical_flow_frames/frame_" + to_string(counter) + ".jpg"; |
| 54 | + imwrite(save_path, bgr); |
| 55 | + } |
| 56 | + imshow("frame", frame2); |
| 57 | + imshow("flow", bgr); |
| 58 | + int keyboard = waitKey(30); |
| 59 | + if (keyboard == 'q' || keyboard == 27) |
| 60 | + break; |
| 61 | + prvs = next; |
| 62 | + counter++; |
| 63 | + } |
| 64 | +} |
| 65 | + |
0 commit comments