1
+ #include < iostream>
2
+ #include < opencv2\opencv.hpp>
3
+
4
+ using namespace cv ;
5
+ using namespace std ;
6
+
7
+ // Function to compute the optical flow map
8
+ void drawOpticalFlow (const Mat& flowImage, const Mat& flowImageGray)
9
+ {
10
+ int stepSize = 16 ;
11
+ Scalar color = Scalar (0 , 255 , 0 );
12
+
13
+ // Draw the uniform grid of points on the input image along with the motion vectors
14
+ for (int y = 0 ; y < flowImageGray.rows ; y += stepSize)
15
+ {
16
+ for (int x = 0 ; x < flowImageGray.cols ; x += stepSize)
17
+ {
18
+ // Circles to indicate the uniform grid of points
19
+ circle (flowImageGray, Point (x, y), 1 , color, FILLED);
20
+
21
+ // Lines to indicate the motion vectors
22
+ const Point2f& pt = flowImage.at <Point2f>(y, x);
23
+ line (flowImageGray, Point (x, y), Point (cvRound (x + pt.x ), cvRound (y + pt.y )), color);
24
+ }
25
+ }
26
+ }
27
+
28
+ void main ()
29
+ {
30
+ String window = " OpticalFlow :: Farneback" ;
31
+ VideoCapture capture (0 );
32
+ Mat prev_gray;
33
+
34
+ // crear la ventana
35
+ namedWindow (window);
36
+
37
+ // bucle de captura de video
38
+ while (true ) {
39
+
40
+ Mat frame, gray, flow;
41
+
42
+ // capturar el cuadro actual
43
+ capture >> frame;
44
+
45
+ // si no hay datos continuar
46
+ if (frame.empty ()) continue ;
47
+
48
+ // escalar a la mitad, para mejorar rendimiento
49
+ resize (frame, frame, Size (), 0.6 , 0.6 , INTER_LINEAR);
50
+
51
+ // convertir a escala de grises
52
+ cvtColor (frame, gray, COLOR_BGR2GRAY);
53
+
54
+ if (!prev_gray.empty ())
55
+ {
56
+ calcOpticalFlowFarneback (prev_gray, gray, flow, 0.5 , 3 , 15 , 3 , 5 , 1.1 , 0 );
57
+ drawOpticalFlow (flow, frame);
58
+ }
59
+
60
+ // esperar por 30 ms ha que se presione una tecla
61
+ if (waitKey (30 ) == 27 ) break ;
62
+
63
+ // mostrar la imagen
64
+ imshow (window, frame);
65
+
66
+ // intercambiar las imagenes, la actual es ahora la anterior.
67
+ cv::swap (prev_gray, gray);
68
+ }
69
+ }
0 commit comments