如何在opencv python中获取视频的前一帧
作者:互联网
我想根据视频的大小增加来检测障碍物.为此,我首先在灰色图像上应用了SIFT以获取当前帧的特征点.接下来,要将当前帧的特征点与上一帧进行比较,我想应用蛮力算法.为此,我想在上一帧中获取特征点.如何在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()
解决方法:
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()
标签:video-processing,opencv,python 来源: https://codeday.me/bug/20191110/2013990.html