How to capture images every n seconds from always running video?

Question:

I want to capture image and store it on my local system after every n seconds, I can not set frame(5) as I want video and detection to run completely. Currently my code is capturing image whenever a condition is failed.

def create_alert(self):
        count = 0
        cap = cv2.VideoCapture(0)
        while cap.isOpened():
            r,f = cap.read()
            try:
                info = ppe.detection(f)
                x,y,w,h,label,conf = info[0]
                if label == "lineman_fail":
                    # engine.say("Warning")
                    # engine.runAndWait()

                    ppe.take_screenshot(f,count)
                    count+=1
                    print(count)
                    print("Something wrong")

                    # cv2.imwrite("img_"+str(count)+".jpg",f)

            except Exception as e:
                print("_______-",e)

            cv2.imshow("image",f)

            if cv2.waitKey(1) & 0xFF == ord("q") :
                break

        cap.release()
        cv2.destroyAllWindows()

    def take_screenshot(self,frame,count):
        prev = time.time()
        cv2.imwrite("screen_shot/img_"+str(count)+".jpg",frame)
Asked By: DholuBholu

||

Answers:

In order to capture image every n seconds try using datetime library, and find the difference between current time and elapsed time. Then use cv2’s imwrite

    while True:
        current = time()

        yolo_v4.delta += current - previous
        previous = current
        frame = camera.get_frame()

if yolo_v4.delta > 10:
    
    ct=datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
    
    cv2.imwrite("screen_shot/img_"+str(ct)+".jpg",frame)
Answered By: Iamgroot
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.