Musa
Musa

Reputation: 119

frame difference using python

I'm trying to do frame difference this is my code below

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

my problem is that I tried to create empty frame to save the first frame from current_frame

previous_frame=np.zeros(current_frame.shape,dtype=current_frame.dtype)

But I think it is not correct , then I tried to pass current_frame like this:

previous_frame=current_frame

Now I'm getting this error :

current_frame_gray = cv2.cvtColor(current_frame, cv2.COLOR_BGR2GRAY) TypeError: src is not a numpy array, neither a scalar

so what should I do for this ?

Thanks for help

Upvotes: 2

Views: 11730

Answers (1)

Elad Joseph
Elad Joseph

Reputation: 3068

You have mixed the VideoCapture object and the frame.

I've also made small changes in the frame copy and waitkey.

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

Upvotes: 4

Related Questions