如何在opencv python中获取视频的前一帧

时间:2017-12-29 16:44:40

标签: python opencv video-processing

我想根据视频的增大来检测视频中的障碍物。首先,我在灰度图像上应用SIFT来获取当前帧的特征点。接下来比较当前帧的特征点和前一帧我想要应用Brute-Force算法。为此我想在前一帧中获得特征点。如何在opencv python中访问前一帧?以及当前帧是视频的第一帧时如何避免访问前一帧?

下面是用python编写的代码,用于获取当前帧的特征点。

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()

3 个答案:

答案 0 :(得分:3)

OpenCV中没有特定的功能来访问前一帧。在进入while循环之前调用cap.read()一次可以解决您的问题。使用变量prev_frame在读取新帧之前存储前一帧。最后,作为一种好的做法,您应该在对其进行计算之前验证框架是否已正确读取。您的代码可能类似于:

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()

答案 1 :(得分:0)

只需将当前帧保存为下一次迭代中的前一帧。如果您需要超过1,请使用列表。

import cv2
import numpy as np


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

while(cap.isOpened()):

  ret, frame = cap.read()

  if previousFrame is not None:
      #use previous frame here
      pass

  #save current frame
  previousFrame=frame


  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()

答案 2 :(得分:0)

您还可以获取/设置从零开始的帧索引(CAP_PROP_POS_FRAMES),如果您希望灵活地返回多个帧,与特定帧进行比较等,这可能很有用。请注意,这会重置下一个read()的位置,所以如果你真的只想要前一帧,那么根据其他答案将它存储在一个变量中可能会更好。

next_frame = cap.get(cv2.CAP_PROP_POS_FRAMES)
current_frame = next_frame - 1
previous_frame = current_frame - 1

if previous_frame >= 0:
  cap.set(cv2.CAP_PROP_POS_FRAMES, previous_frame)
  ret, frame = cap.read()