Nemi Bhattarai
Nemi Bhattarai

Reputation: 181

Processing frame every second in opencv python

Here is the code for reading video file from webcam using opencv website. I just want to process the frame every second.

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

How should I modify the code:

Upvotes: 2

Views: 5498

Answers (1)

Benjamin Barrois
Benjamin Barrois

Reputation: 2686

You should just make your process wait for one second before each read:

import numpy as np
import cv2
import time

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    start_time = time.time()
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',gray)

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

    time.sleep(1.0 - time.time() + start_time) # Sleep for 1 second minus elapsed time

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

Upvotes: 0

Related Questions