work on optical flow sample
authorAlexander Mordvintsev <no@email>
Wed, 6 Jul 2011 19:02:40 +0000 (19:02 +0000)
committerAlexander Mordvintsev <no@email>
Wed, 6 Jul 2011 19:02:40 +0000 (19:02 +0000)
samples/python2/opt_flow.py [new file with mode: 0644]

diff --git a/samples/python2/opt_flow.py b/samples/python2/opt_flow.py
new file mode 100644 (file)
index 0000000..1c30294
--- /dev/null
@@ -0,0 +1,38 @@
+import numpy as np\r
+import cv2, cv\r
+import video\r
+import sys\r
+\r
+try: fn = sys.argv[1]\r
+except: fn = video.presets['chess']\r
+\r
+cam = video.create_capture(fn)\r
+ret, prev = cam.read()\r
+#prev = cv2.pyrDown(prev)\r
+prevgray = cv2.cvtColor(prev, cv.CV_BGR2GRAY)\r
+\r
+def draw_flow(img, flow, step):\r
+    h, w = img.shape[:2]\r
+    y, x = map(np.ravel, np.mgrid[step/2:h:step, step/2:w:step])\r
+    f = flow[y,x]\r
+    x1 = x + f[:,0]\r
+    y1 = y + f[:,1]\r
+    #lines = np.int32( np.vstack([x, y, x1, y1]).T )\r
+    vis = cv2.cvtColor(img, cv.CV_GRAY2BGR)\r
+    #print lines\r
+    #cv2.polylines(vis, lines, 0, (0, 255, 0))\r
+    for x_, y_, x1_, y1_ in np.int32(zip(x, y, x1, y1)):\r
+        cv2.line(vis, (x_, y_), (x1_, y1_), (0, 255, 0))\r
+    return vis\r
+\r
+while True:\r
+    ret, img = cam.read()\r
+    #img = cv2.pyrDown(img)\r
+    gray = cv2.cvtColor(img, cv.CV_BGR2GRAY)\r
+    flow = cv2.calcOpticalFlowFarneback(prevgray, gray, 0.5, 3, 15, 3, 5, 1.2, 0)\r
+    prevgray = gray\r
+\r
+    cv2.imshow('flow', draw_flow(gray, flow, 16))\r
+    if cv2.waitKey(5) == 27:\r
+        break\r
+\r