opt_flow.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #!/usr/bin/env python
  2. '''
  3. example to show optical flow
  4. USAGE: opt_flow.py [<video_source>]
  5. Keys:
  6. 1 - toggle HSV flow visualization
  7. 2 - toggle glitch
  8. Keys:
  9. ESC - exit
  10. '''
  11. # Python 2/3 compatibility
  12. from __future__ import print_function
  13. import numpy as np
  14. import cv2 as cv
  15. import video
  16. def draw_flow(img, flow, step=16):
  17. h, w = img.shape[:2]
  18. y, x = np.mgrid[step/2:h:step, step/2:w:step].reshape(2,-1).astype(int)
  19. fx, fy = flow[y,x].T
  20. lines = np.vstack([x, y, x+fx, y+fy]).T.reshape(-1, 2, 2)
  21. lines = np.int32(lines + 0.5)
  22. vis = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
  23. cv.polylines(vis, lines, 0, (0, 255, 0))
  24. for (x1, y1), (_x2, _y2) in lines:
  25. cv.circle(vis, (x1, y1), 1, (0, 255, 0), -1)
  26. return vis
  27. def draw_hsv(flow):
  28. h, w = flow.shape[:2]
  29. fx, fy = flow[:,:,0], flow[:,:,1]
  30. ang = np.arctan2(fy, fx) + np.pi
  31. v = np.sqrt(fx*fx+fy*fy)
  32. hsv = np.zeros((h, w, 3), np.uint8)
  33. hsv[...,0] = ang*(180/np.pi/2)
  34. hsv[...,1] = 255
  35. hsv[...,2] = np.minimum(v*4, 255)
  36. bgr = cv.cvtColor(hsv, cv.COLOR_HSV2BGR)
  37. return bgr
  38. def warp_flow(img, flow):
  39. h, w = flow.shape[:2]
  40. flow = -flow
  41. flow[:,:,0] += np.arange(w)
  42. flow[:,:,1] += np.arange(h)[:,np.newaxis]
  43. res = cv.remap(img, flow, None, cv.INTER_LINEAR)
  44. return res
  45. def main():
  46. import sys
  47. try:
  48. fn = sys.argv[1]
  49. except IndexError:
  50. fn = 0
  51. cam = video.create_capture(fn)
  52. _ret, prev = cam.read()
  53. prevgray = cv.cvtColor(prev, cv.COLOR_BGR2GRAY)
  54. show_hsv = False
  55. show_glitch = False
  56. cur_glitch = prev.copy()
  57. while True:
  58. _ret, img = cam.read()
  59. gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
  60. flow = cv.calcOpticalFlowFarneback(prevgray, gray, None, 0.5, 3, 15, 3, 5, 1.2, 0)
  61. prevgray = gray
  62. cv.imshow('flow', draw_flow(gray, flow))
  63. if show_hsv:
  64. cv.imshow('flow HSV', draw_hsv(flow))
  65. if show_glitch:
  66. cur_glitch = warp_flow(cur_glitch, flow)
  67. cv.imshow('glitch', cur_glitch)
  68. ch = cv.waitKey(5)
  69. if ch == 27:
  70. break
  71. if ch == ord('1'):
  72. show_hsv = not show_hsv
  73. print('HSV flow visualization is', ['off', 'on'][show_hsv])
  74. if ch == ord('2'):
  75. show_glitch = not show_glitch
  76. if show_glitch:
  77. cur_glitch = img.copy()
  78. print('glitch is', ['off', 'on'][show_glitch])
  79. print('Done')
  80. if __name__ == '__main__':
  81. print(__doc__)
  82. main()
  83. cv.destroyAllWindows()