user6745741 user6745741 - 2 months ago 18
Python Question

How to set time limit in real time video capturing?

I have code that capture video from camera.The frames captured are append to a list.But how to set time limit to this capture?.I only want to capture the first two minutes after that the recording must stop.My code is

import cv2
import numpy

#creating video capture object
capture=cv2.VideoCapture(0)

#Set the resolution of capturing to 640W*480H
capture.set(3,640)
capture.set(4,480)
frame_set=[]
while(True):
# Capture frame-by-frame
ret, frame = capture.read()

# Converting to Gray Scale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
frame_set.append(gray)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

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

Answer

Use time package

import cv2
import numpy
import time
capture=cv2.VideoCapture(0)
capture.set(3,640)
capture.set(4,480)
frame_set=[]
start_time=time.time()
while(True):
    ret, frame = capture.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    frame_set.append(gray)
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    end_time=time.time()
    elapsed = end_time - start_time
    if elapsed > 120:
       break
 capture.release()
 cv2.destroyAllWindows()
Comments