Search code examples
pythonopencvvideo-processing

How to get previous frame of a video in opencv python


I want to detect obstacles from a video based on their increasing size.To do that first I applied SIFT on gray image to get feature points of current frame. Next to compare the feature points of current frame with the previous frame I want to apply Brute-Force algorithm. For that I want to get feature points in previous frame. How can I access previous frame in opencv python ? and how to avoid accessing previous frame when the current frame is the first frame of the video?

below is the code written in python to get feature points of current frame.

import cv2
import numpy as np


cap = cv2.VideoCapture('video3.mov')

  while(cap.isOpened()):

  ret, frame = cap.read()

  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

  #detect key feature points
  sift = cv2.xfeatures2d.SIFT_create()
  kp, des = sift.detectAndCompute(gray, None)

 #draw key points detected
 img=cv2.drawKeypoints(gray,kp,gray,flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

 cv2.imshow("grayframe",img)

 if cv2.waitKey(100) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

Solution

  • There is no specific function in OpenCV to access the previous frame. Your problem can be solved by calling cap.read() once before entering the while loop. Use a variable prev_frame to store the previous frame just before reading the new frame. Finally, as a good practice, you should verify that the frame was properly read, before doing computations on it. Your code could look something like:

    import cv2
    import numpy as np
    
    cap = cv2.VideoCapture('video3.mov')
    ret, frame = cap.read()
    
    while(cap.isOpened()):
        prev_frame=frame[:]
        ret, frame = cap.read()
        if ret:
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
            #detect key feature points
            sift = cv2.xfeatures2d.SIFT_create()
            kp, des = sift.detectAndCompute(gray, None)
    
            #some magic with prev_frame
    
            #draw key points detected
            img=cv2.drawKeypoints(gray,kp,gray, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
    
            cv2.imshow("grayframe",img)
        else:
            print('Could not read frame')
    
        if cv2.waitKey(100) & 0xFF == ord('q'):
            break
    
    cap.release()
    cv2.destroyAllWindows()