sentientnativeplant
sentientnativeplant

Reputation: 63

How do I end a loop within a loop after 10 seconds?

I am working with opencv and instead of using the typical while loop on a video I am running an extra while loop inside for other functions. My goal is for the second while loop after activated to end and break all the loops after 10 seconds.

So far I used datetime to create a time_start variable and then tried to find the change of time with the time_delta variable and the while loop should break after it reaches a value of 10. I only have a couple weeks of python experience so I am probably making a simple mistake. Here is the code I am trying to execute (you can ignore the 'MAIN FUNCTIONS' code):

start_time = datetime.datetime.now()
end_time = 0

while end_time < datetime.datetime.now():

    ret, frame = cap.read( )

    if point1 and point2:

        end_time =start_time + datetime.timedelta(seconds=10)

        if has_run == 0:
            gray_get()
            has_run = 1


        ######### MAIN FUNCTIONS ######################################
        cv2.rectangle(frame, point1, point2, (0, 0, 0), 2)
        first_frame_roi = first_frame[point1[1]:point2[1], point1[0]:point2[0]]
        cropped_window = frame[point1[1]:point2[1], point1[0]:point2[0], :]
        gray = cv2.cvtColor(cropped_window, cv2.COLOR_BGR2GRAY)
        flow = cv2.calcOpticalFlowFarneback(prev_gray, gray, None,.5, 6, 15, 3, 5, 1.1, 0)
        prev_gray = gray
        mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])
        mag_list.append(mag)
        cv2.imshow('optical flow', draw_flow(gray, flow))
        #################################################################

    cv2.imshow('Original', frame)

    key = cv2.waitKey(30) & 0xff
    if key == 27:
         break

cap.release()
cv2.destroyAllWindows()

Upvotes: 1

Views: 1692

Answers (2)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

Another way of running a while loop for 10 seconds is using datetime module.

import datetime

start_time = datetime.datetime.now()
#end time is 10 sec after the current time
end_time = start_time + datetime.timedelta(seconds=10)

#Run the loop till current time exceeds end time
while end_time > datetime.datetime.now():
    #do stuff

An advantage here is you can also define time intervals in minutes and hours using the datetime.timedelta function

Upvotes: 2

Ben
Ben

Reputation: 9703

import time
endTime_s = time.time() + 10.0
while time.time() < endTime_s:
    doStuff()

Upvotes: 0

Related Questions