Reputation: 21
I am currently writing a program that uses openCV with a haar cascade for eyes. I need it to run some code if eyes are not detected for a few seconds, and I can't figure out how to use the time library to check the time. Here is an example of something I have tried.
if len(eyes) == 0:
if noEyeTime - startTime > 2:
print("closed for more than 2 seconds")
time.sleep(2)
startTime = time.time()
noEyeTime = time.time()
# The variables are declared outside of the while loop
This is the check that I've written (it's inside a while True loop), and I've tried moving around the variable updates but I can't figure out how to check if eyes have not been detected for x amount of time.
I also read this post: Python if condition true for x amount of time
But the solution doesn't work for me because the program still needs to be running, so time.sleep() is not an option.
Thanks in advance.
Upvotes: 0
Views: 229
Reputation: 21
Thanks to Ritesh's idea, I moved the startTime to where the eyes are detected, and then compared that to the current time when the eyes are not detected. The code looks like this:
# Writes to log file when eyes are detected
if anterior != len(eyes):
anterior = len(eyes)
log.info("faces: "+str(len(eyes))+" at "+str(dt.datetime.now()))
startTime = time.time()
if len(eyes) == 0:
elapsedTime = endingTime - startTime
if elapsedTime > 2:
print("eyes closed for 2 seconds")
endingTime = time.time()
Upvotes: 1
Reputation: 146
you can have a time track by creating an starting_noEye=time.time()
before starting eye no eye detection and an ending_noEye=time.time()
at the end of the no eye detection part of code. The noEyeTime can be assigned to differenence of those :- noEyeTime=ending_noEye-starting_noEye
. This will give you the amount of time when eyes were not detected.
Upvotes: 1