简体   繁体   中英

Get the current frame from USB camera using opencv

I'm using opencv's VideoCapture() to read frames from a USB camera. What I want is getting still images at some random time.

What I have now is that I initialize the cap using:

cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)

Then use this bit of code to get frame:

ret, frame = cap.read()

I can get the first frame correctly. However, it seems the next time I acquire a frame (after a random time gap), it is not the frame at that time, but the consecutive frame next to the first one (almost the same as the first frame).

I also tried to release the cap after the first time and get a new cap for the second capture. But initialing the cap takes around 1 second, which is too long and cannot be accepted.

Is there any solution to this problem?

Thanks.

A solution is to continually capture frames, but only display a frame after a random time gap.

Wait a random number of frames:

    import random
    import cv2

    cap = cv2.VideoCapture(0)

    def wait(delay):
            framecount = 0
            # capture and discard frames while the delay is not over
            while framecount < delay:
                    cap.read()
                    framecount += 1

    while True:
            # select and wait random number of delay frames
            delay = random.randint(50,150)
            wait(delay)
            # get and display next frame
            ret, img = cap.read()
            cv2.imshow("Image", img)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                    break

    cv2.destroyAllWindows()  

Random time wait:

    import time
    import random
    import cv2

    curr_time = time.time()
    cap = cv2.VideoCapture(0)

    def wait(delay):
            # capture and discard frames while the delay is not over
            while time.time()-curr_time < delay:
                    cap.read()

    while True:
            # select and wait random delay time
            delay = random.random()
            wait(delay)
            # update curr_time
            curr_time = time.time()
            # get and display next frame
            ret, img = cap.read()
            cv2.imshow("Image", img)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                    break

    cv2.destroyAllWindows()   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM