Search code examples
pythonopencvtimeimage-capture

Terminate a Python script after a time period


My code does capture images every 2 secs. But the problem is it runs endlessly. I need the script to terminate or close at a time period (i.e like terminate or close after 50secs). I tried using sleep() but suspects that doesn't terminate the whole script or closes it, It just puts the script to sleep ! Hope someone could help me with terminating the script after a time period!

My script :

import cv2
import numpy
import time

capture = cv2.VideoCapture(0)
capture.set(3, 640)
capture.set(4, 480)
img_counter = 0
frame_set = []
start_time = time.time()

while True:
    ret, frame = capture.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame', gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    if time.time() - start_time >= 2:
        img_name = "FaceFrame{}.jpg".format(img_counter)
        cv2.imwrite(img_name, frame)
        print("{} written!".format(img_counter))
        start_time = time.time()
    img_counter += 1

Solution

  • actual_start_time = time.clock()
    start_time = time.time()
    while ((time.clock() - actual_start_time) < 50):
        #do stuff
    

    Alternatively:

    actual_start_time = time.clock()
    start_time = time.time()
    while True:
        #do stuff
        if (time.clock() - actual_start_time) > 50):
            break