使用python的帧差异

时间:2015-11-25 20:38:22

标签: python opencv numpy

我正在尝试做框架差异,这是我的代码

import numpy as np
import cv2

current_frame =cv2.VideoCapture(0)


previous_frame=current_frame


while(current_frame.isOpened()):


current_frame_gray = cv2.cvtColor(current_frame, cv2.COLOR_BGR2GRAY)
previous_frame_gray= cv2.cvtColor(previous_frame, cv2.COLOR_BGR2GRAY)

frame_diff=cv2.absdiff(current_frame_gray,previous_frame_gray)


cv2.imshow('frame diff ',frame_diff)


cv2.waitKey(1)

current_frame.copyto(previous_frame)
ret, current_frame = current_frame.read()


current_frame.release()
cv2.destroyAllWindows()

我的问题是我尝试创建空帧以保存current_frame

中的第一帧
previous_frame=np.zeros(current_frame.shape,dtype=current_frame.dtype)

但我认为这是不正确的,然后我试图像这样传递current_frame:

previous_frame=current_frame

现在我收到了这个错误:

  

current_frame_gray = cv2.cvtColor(current_frame,cv2.COLOR_BGR2GRAY)   TypeError:src不是一个numpy数组,也不是标量

那我该怎么做呢?

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您已混合VideoCapture对象和框架。

我还对帧复制和等待键做了一些小改动。

import cv2

cap = cv2.VideoCapture(0)
ret, current_frame = cap.read()
previous_frame = current_frame

while(cap.isOpened()):
    current_frame_gray = cv2.cvtColor(current_frame, cv2.COLOR_BGR2GRAY)
    previous_frame_gray = cv2.cvtColor(previous_frame, cv2.COLOR_BGR2GRAY)    

    frame_diff = cv2.absdiff(current_frame_gray,previous_frame_gray)

    cv2.imshow('frame diff ',frame_diff)      
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

    previous_frame = current_frame.copy()
    ret, current_frame = cap.read()

cap.release()
cv2.destroyAllWindows()