motempl.py 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #!/usr/bin/env python
  2. import numpy as np
  3. import cv2 as cv
  4. MHI_DURATION = 0.5
  5. DEFAULT_THRESHOLD = 32
  6. MAX_TIME_DELTA = 0.25
  7. MIN_TIME_DELTA = 0.05
  8. # (empty) trackbar callback
  9. def nothing(dummy):
  10. pass
  11. def draw_motion_comp(vis, rect, angle, color):
  12. x, y, w, h = rect
  13. cv.rectangle(vis, (x, y), (x+w, y+h), (0, 255, 0))
  14. r = min(w//2, h//2)
  15. cx, cy = x+w//2, y+h//2
  16. angle = angle*np.pi/180
  17. cv.circle(vis, (cx, cy), r, color, 3)
  18. cv.line(vis, (cx, cy), (int(cx+np.cos(angle)*r), int(cy+np.sin(angle)*r)), color, 3)
  19. if __name__ == '__main__':
  20. import sys
  21. try:
  22. video_src = sys.argv[1]
  23. except:
  24. video_src = 0
  25. cv.namedWindow('motempl')
  26. visuals = ['input', 'frame_diff', 'motion_hist', 'grad_orient']
  27. cv.createTrackbar('visual', 'motempl', 2, len(visuals)-1, nothing)
  28. cv.createTrackbar('threshold', 'motempl', DEFAULT_THRESHOLD, 255, nothing)
  29. cam = cv.VideoCapture(video_src)
  30. if not cam.isOpened():
  31. print("could not open video_src " + str(video_src) + " !\n")
  32. sys.exit(1)
  33. ret, frame = cam.read()
  34. if ret == False:
  35. print("could not read from " + str(video_src) + " !\n")
  36. sys.exit(1)
  37. h, w = frame.shape[:2]
  38. prev_frame = frame.copy()
  39. motion_history = np.zeros((h, w), np.float32)
  40. hsv = np.zeros((h, w, 3), np.uint8)
  41. hsv[:,:,1] = 255
  42. while True:
  43. ret, frame = cam.read()
  44. if ret == False:
  45. break
  46. frame_diff = cv.absdiff(frame, prev_frame)
  47. gray_diff = cv.cvtColor(frame_diff, cv.COLOR_BGR2GRAY)
  48. thrs = cv.getTrackbarPos('threshold', 'motempl')
  49. ret, motion_mask = cv.threshold(gray_diff, thrs, 1, cv.THRESH_BINARY)
  50. timestamp = cv.getTickCount() / cv.getTickFrequency()
  51. cv.motempl.updateMotionHistory(motion_mask, motion_history, timestamp, MHI_DURATION)
  52. mg_mask, mg_orient = cv.motempl.calcMotionGradient( motion_history, MAX_TIME_DELTA, MIN_TIME_DELTA, apertureSize=5 )
  53. seg_mask, seg_bounds = cv.motempl.segmentMotion(motion_history, timestamp, MAX_TIME_DELTA)
  54. visual_name = visuals[cv.getTrackbarPos('visual', 'motempl')]
  55. if visual_name == 'input':
  56. vis = frame.copy()
  57. elif visual_name == 'frame_diff':
  58. vis = frame_diff.copy()
  59. elif visual_name == 'motion_hist':
  60. vis = np.uint8(np.clip((motion_history-(timestamp-MHI_DURATION)) / MHI_DURATION, 0, 1)*255)
  61. vis = cv.cvtColor(vis, cv.COLOR_GRAY2BGR)
  62. elif visual_name == 'grad_orient':
  63. hsv[:,:,0] = mg_orient/2
  64. hsv[:,:,2] = mg_mask*255
  65. vis = cv.cvtColor(hsv, cv.COLOR_HSV2BGR)
  66. for i, rect in enumerate([(0, 0, w, h)] + list(seg_bounds)):
  67. x, y, rw, rh = rect
  68. area = rw*rh
  69. if area < 64**2:
  70. continue
  71. silh_roi = motion_mask [y:y+rh,x:x+rw]
  72. orient_roi = mg_orient [y:y+rh,x:x+rw]
  73. mask_roi = mg_mask [y:y+rh,x:x+rw]
  74. mhi_roi = motion_history[y:y+rh,x:x+rw]
  75. if cv.norm(silh_roi, cv.NORM_L1) < area*0.05:
  76. continue
  77. angle = cv.motempl.calcGlobalOrientation(orient_roi, mask_roi, mhi_roi, timestamp, MHI_DURATION)
  78. color = ((255, 0, 0), (0, 0, 255))[i == 0]
  79. draw_motion_comp(vis, rect, angle, color)
  80. cv.putText(vis, visual_name, (20, 20), cv.FONT_HERSHEY_PLAIN, 1.0, (200,0,0))
  81. cv.imshow('motempl', vis)
  82. prev_frame = frame.copy()
  83. if 0xFF & cv.waitKey(5) == 27:
  84. break
  85. # cleanup the camera and close any open windows
  86. cam.release()
  87. cv.destroyAllWindows()