1

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

1 Answers1

3
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
ycx
  • 3,155
  • 3
  • 14
  • 26
  • Shouldn't that be less than? and the outer parenthesese aren't exactly needed – Jab Feb 28 '19 at 05:42
  • @Jab I fixed it before your comment. Also, the outer brackets are personal choice. I find it to improve clarity – ycx Feb 28 '19 at 05:45
  • 1
    No issue, and yes that's why I said they aren't exactly needed, can see the improved readability. also technically `exit()` feels more proper if OP truly wants to "terminate the script" – Jab Feb 28 '19 at 05:47
  • @Jab You're technically right on `exit()`. In the off-chance that asker decides to extend his script though, that could totally break it. Best to let the script close itself, no? – ycx Feb 28 '19 at 05:53
  • I can use time.time() right ? instead of time.clock() .. No issues right? –  Feb 28 '19 at 06:24
  • @Sai Not much difference unless your script is absolutely time-critical. It depends on your OS. Unix and Windows have different implementations of `time.time()` and `time.clock()`. It has to do with precision and accuracy. See: https://www.pythoncentral.io/measure-time-in-python-time-time-vs-time-clock/ for more information. – ycx Feb 28 '19 at 06:27
  • @Sai I saw your script and realised you did another assignment of `start_time`. I've edited the script to include another variable `actual_start_time` for your script to keep track of it so that the `start_time` can still be used without issue by your image capture timer – ycx Feb 28 '19 at 06:34