Created
          April 28, 2021 07:33 
        
      - 
      
 - 
        
Save devymex/298fdb47bb4734903de0dd3670e4628f to your computer and use it in GitHub Desktop.  
    play video frame by frame
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | #!/usr/bin/python3 | |
| import sys, cv2 | |
| video_file = sys.argv[1] | |
| video = cv2.VideoCapture(video_file) | |
| assert video.isOpened() | |
| frame_cnt = int(video.get(cv2.CAP_PROP_FRAME_COUNT)) | |
| def read_frame(pos): | |
| video.set(cv2.CAP_PROP_POS_FRAMES, pos) | |
| ret, img = video.read() | |
| assert ret | |
| cv2.putText(img, '{}/{}'.format(pos + 1, frame_cnt), (10, 40), | |
| cv2.FONT_HERSHEY_SIMPLEX, 1.0,(0, 255, 0), 1, cv2.LINE_AA) | |
| return img | |
| iframe = 0 | |
| cur_img = [] | |
| playing = False | |
| while True: | |
| if int(video.get(cv2.CAP_PROP_POS_FRAMES)) != iframe + 1: | |
| cur_img = read_frame(iframe) | |
| cv2.imshow('frame', cur_img) | |
| key = cv2.waitKey(40 if playing else 0) & 0xFF | |
| if key == 27: | |
| break | |
| elif key == 32: | |
| playing = not playing | |
| if playing: | |
| iframe += 1 | |
| if iframe >= frame_cnt: | |
| iframe = frame_cnt - 1 | |
| playing = False | |
| else: | |
| if key == 81: | |
| iframe = max(iframe - 1, 0) | |
| elif key == 83: | |
| iframe = min(iframe + 1, frame_cnt - 1) | |
| elif key == 82: | |
| iframe = 0 | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment