I've had success in Python 3 using a simple counter and setting the capture to that counter's frame, as follows:

import cv2

cap = cv2.VideoCapture('XYZ.avi')
# For streams:
#   cap = cv2.VideoCapture('rtsp://url.to.stream/media.amqp')
# Or e.g. most common ID for webcams:
#   cap = cv2.VideoCapture(0)
count = 0

while cap.isOpened():
    ret, frame = cap.read()

    if ret:
        cv2.imwrite('frame{:d}.jpg'.format(count), frame)
        count += 30 # i.e. at 30 fps, this advances one second
        cap.set(cv2.CAP_PROP_POS_FRAMES, count)
    else:
        cap.release()
        break

I've tried to find a way to make this a little more pythonic using a with statement but I don't believe the CV2 library has been updated for it.

Answer from benJephunneh on Stack Overflow
Discussions

python - OpenCV - How to get only first frame and skip other frames when servo function is called - Stack Overflow
my project I'm working on is face recognition. The face recognition bit works fine. However when the face is recognised, and the servo opens the door and closes after seconds. Servo keeps opening the More on stackoverflow.com
🌐 stackoverflow.com
c++ - Reading every nth frame from VideoCapture in OpenCV - Stack Overflow
Is it possible to read frames from a video in steps (eg I want to read every fifth frame of a video stream). Currently I'm doing this as a workaround but it's not very effecient. bool bSuccess int More on stackoverflow.com
🌐 stackoverflow.com
python - Skip frames and seek to end of RTSP stream in OpenCV - Stack Overflow
I capture and process an IP camera RTSP stream in a OpenCV 3.4.2 on Raspberry Pi. Unfortunately the processing takes quite a lot of time, roughly 0.2s per frame, and the stream quickly gets delayed... More on stackoverflow.com
🌐 stackoverflow.com
[Question] How to capture a picture after every 5 seconds of camera using opencv python and Raspbery Pi 3?
Not an expert, but is the problem from using an avi to test with? I'd expect the cap.read() to always get the next frame from an avi causing it to appear to pause for 5 seconds. i.e get frame 0, wait 5 sec, get frame 1, wait 5 sec, get frame 2 etc. With a live camera, I'd expect cap.read() to get the currently visible frame, so no pause? edit: reading the docs for VideoCapture.set(), it looks like you can set the current position in the avi file, either in milliseconds or frames. More on reddit.com
🌐 r/opencv
7
2
March 15, 2018
🌐
OpenCV Q&A Forum
answers.opencv.org › question › 24714 › skipping-frames-in-videocapture
Skipping frames in VideoCapture - OpenCV Q&A Forum
Using this method you can set the CV_CAP_PROP_POS_FRAMES property to the frame number you want to quickly bypass however many frames you want. For example, in python 3 you would do it as:
🌐
IQCode
iqcode.com › code › python › opencv-skip-video-frames
opencv skip video frames Code Example
November 11, 2021 - import cv2 cap = cv2.VideoCapture('path/to/video/file') start_frame_number = 50 cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame_number) # Now when you read the frame, you will be reading the 50th frame success, frame = cap.read() ... Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond. Sign up · Develop soft skills on BrainApps Complete the IQ Test ... opencv video skip frames cv2 videocapture skip frames opencv skip frames opencv skip n frames skip frames seconds opencv python opencv skip in video skip frame opencv opencv skip seconds frameskipping opencv frameskipping a videoin python how to skip frames before detection opencv python read lattest frame skipp missing skip frames opencv python how to capture a video using opencv at 1 frame per 2 sec cap.read skip frame
🌐
Stack Overflow
stackoverflow.com › questions › 50430732 › opencv-how-to-get-only-first-frame-and-skip-other-frames-when-servo-function-i › 50430775
python - OpenCV - How to get only first frame and skip other frames when servo function is called - Stack Overflow
import cv2 import time import RPi.GPIO as GPIO import numpy as np import threading class main: def servo(self): print ("door open") GPIO.setmode(GPIO.BOARD) GPIO.setup(11,GPIO.OUT) pwm=GPIO.PWM(11,50) pwm.start(8) time.sleep(5.20) pwm.ChangeDutyCycle(3) def face(self): recognizer = cv2.face.LBPHFaceRecognizer_create() recognizer.read('trainner/trainner.yml') cascadePath = "haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(cascadePath); cam = cv2.VideoCapture(0) font = cv2.FONT_HERSHEY_SIMPLEX num = 1 while True: ret, frame =cam.read() gray=cv2.cvtColor(frame,cv2.COLOR_BG
🌐
Iditect
iditect.com › program-example › python--skip-frames-and-seek-to-end-of-rtsp-stream-in-opencv.html
python - Skip frames and seek to end of RTSP stream in OpenCV
Skipping Frames: Use a loop to read and discard frames (cap.read()) based on your requirement (frames_to_skip). Seeking to End: OpenCV's VideoCapture for RTSP streams operates in a continuous manner.
🌐
MaxInterview
maxinterview.com › code › opencv-skip-video-frames-3B0A13B45B2389E
MaxInterview - opencv skip video frames
April 4, 2022 - queries leading to this pageopencv skip n frameshow to capture a video using opencv at 1 frame per 2 seccap read skip frameskip frame opencvframeskipping a videoin pythonskip frames opencv pythonopencv skip framescv2 videocapture skip framesopencv python read lattest frame skipp missingskip frames seconds opencv pythonopencv skip in videoframeskipping opencvhow to skip frames before detectionopencv video skip framesopencv skip secondsopencv skip video frames
Find elsewhere
Top answer
1 of 6
18

Try this:

vcap = cv2.VideoCapture("rtspsrc location=rtsp://{IPcam}/12 ! decodebin ! videoconvert ! appsink max-buffers=1 drop=true")

This uses gstreamer to grab your camera feed, and will maintain a buffer of length 1 and drop the oldest as new incoming frames are received. Then, every time you call vcap.read() you should get the latest frame.

You can also try using the OMX decoder on the Raspberry Pi if you notice CPU usage is really high, as this will decode the video (assuming it's h264) on the GPU: ! rtph264depay ! h264parse ! omxh264dec ! appsink max-buffers=1 drop=true

You may need to recompile OpenCV as by default it's compiled with FFMPEG support, not gstreamer. This is fairly simple, just pass -D WITH_GSTREAMER=ON -D WITH_FFMPEG=OFF to the cmake command. Make sure you have the gstreamer development libs installed apt install libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev.

2 of 6
8

I rewrote threading implementation from Shubham into a class, to be able to stream many cameras:

import threading
from threading import Lock
import cv2

class Camera:
    last_frame = None
    last_ready = None
    lock = Lock()

    def __init__(self, rtsp_link):
        capture = cv2.VideoCapture(rtsp_link)
        thread = threading.Thread(target=self.rtsp_cam_buffer, args=(capture,), name="rtsp_read_thread")
        thread.daemon = True
        thread.start()

    def rtsp_cam_buffer(self, capture):
        while True:
            with self.lock:
                self.last_ready, self.last_frame = capture.read()


    def getFrame(self):
        if (self.last_ready is not None) and (self.last_frame is not None):
            return self.last_frame.copy()
        else:
            return None

Then, it can be used as:

capture = Camera('rtsp://...')

while True:
    frame = capture.getFrame()
🌐
Reddit
reddit.com › r/opencv › [question] how to capture a picture after every 5 seconds of camera using opencv python and raspbery pi 3?
r/opencv on Reddit: [Question] How to capture a picture after every 5 seconds of camera using opencv python and Raspbery Pi 3?
March 15, 2018 -

I am working on a school project which is related to Image Processing using OpenCV Python and Raspberry Pi 3.

The hardware of Raspberry Pi 3 cannot handle the video from camera consecutively, therefore I'm thinking about only capture a picture after every 5 seconds from the camera and use it to recognize what I need, then continue.

I did some research on the internet and found a function called time.sleep(5), however this function only pause the camera 5 seconds and then continue.

Can anyone help me to solve my problem. Thank you so much. Sorry for my bad English, here is my code so far. In my code, I use a video to test first, then when figure out the solution, I will apply on camera.

import cv2
import numpy as np
import time

headcc = cv2.CascadeClassifier('lib/heads_cascade.xml')
cap = cv2.VideoCapture('image/hockey_game.avi')

def video():
    ret, frame = cap.read()

    # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    head = headcc.detectMultiScale(frame, 1.2, 2, 0 , (20, 20), (40, 40))

    print type(head)
    print head
    print head.shape
    print "Number of heads detected: " + str(head.shape[0])


    if len(head) > 0:
        for (x, y, w, h) in head:
            cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 255), 1)

    cv2.rectangle(frame, ((0,frame.shape[0] -25)),(270, frame.shape[0]), (255,255,255), -1)
    cv2.putText(frame, "Number of head detected: " + str(head.shape[0]), (0,frame.shape[0] -10), cv2.FONT_HERSHEY_TRIPLEX, 0.5,  (0,0,0), 1)

    cv2.namedWindow('Camera',cv2.WINDOW_NORMAL)
    cv2.imshow('Camera',frame)


while(cap.isOpened()):
    video()
    time.sleep(5)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

Update March 15th, 2018: Thanks to comment from Joe, I have found the way to skip frames. However, the program still cannot know whether the video ends, and also the fps code still appear 0.0. So if there is any help for these errors, I will really appreciate. Here is the code so far:

import cv2
import numpy as np
import time

headcc = cv2.CascadeClassifier('lib/heads_cascade.xml')
cap = cv2.VideoCapture('image/hockey_game.avi')
fps = cap.get(cv2.CAP_PROP_POS_FRAMES)

def video():
    ret, frame = cap.read()

    # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    head = headcc.detectMultiScale(frame, 1.2, 2, 0 , (20, 20), (40, 40))

    # print type(head)
    # print head
    # print head.shape
    print "Number of heads detected: " + str(head.shape[0])

    if len(head) > 0:
        for (x, y, w, h) in head:
            cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 255), 1)

    # cv2.rectangle(frame, ((0,frame.shape[0] -25)),(270, frame.shape[0]), (255,255,255), -1)
    # cv2.putText(frame, "Number of head detected: " + str(head.shape[0]), (0,frame.shape[0] -10), cv2.FONT_HERSHEY_TRIPLEX, 0.5,  (0,0,0), 1)

    cv2.namedWindow('Camera',cv2.WINDOW_NORMAL)
    cv2.imshow('Camera',frame)


while(cap.isOpened()):
    video()
    cf = cap.get(cv2.CAP_PROP_POS_FRAMES) - 1
    cap.set(cv2.CAP_PROP_POS_FRAMES, cf+50)
    # cv2.setTrackbarPos("pos_trackbar", "Frame Grabber", 
int(cap.get(cv2.CAP_PROP_FPS)))
    time.sleep(2)
    if (cv2.waitKey(1) & 0xFF == ord('q')):
        break

print fps
cap.release()
cv2.destroyAllWindows()
🌐
Stack Overflow
stackoverflow.com › questions › 72800224 › skip-frames-and-seek-to-end-of-rtsp-stream-in-opencv-python
skip frames and seek to end of rtsp stream in opencv Python - Stack Overflow
June 29, 2022 - you're gonna have to run the stream reception in a thread, and keep the latest frame around (in a variable) for when you need it. -- you can't throttle the stream. if you don't read in a timely manner, frames WILL QUEUE UP. eventually, the whole ...
🌐
GitHub
github.com › opencv › opencv-python › issues › 439
Any method to skip frames when analyzing an local video file? · Issue #439 · opencv/opencv-python
January 16, 2021 - In my opinion, the method ret, frame = cap.read() includes two parts: read a raw frame data(load data to memory and update related pointer or status?) analyze and translate the raw data to a python unit(BGR[][][] matirx?), and then return the result · I guess there could be a method cap.skip(int n) to optimize the performance:
Author: opencv
🌐
OpenCV
forum.opencv.org › t › how-to-skip-similar-frames › 5001
How to skip similar frames - OpenCV
August 31, 2021 - Hi., I am trying to make a program that detects the face without face mask and write it to the folder in jpg format. I successfully did it., but it writes all the very similar frames of the same person to disk and after 1 minute of detection inference from video file it is about 389 images saved, but originally I need to save about 10 images from the whole video to the disk.
🌐
OpenCV Q&A Forum
answers.opencv.org › question › 94012 › is-opencvs-videocaptureread-function-skipping-frames
Is OpenCV's VideoCapture.read() function skipping frames? - OpenCV Q&A Forum
However, I've noticed that the time I calculate is incorrect even for very simple test cases. I think I've tracked the problem down to OpenCV's VideoCapture.read() function. It doesn't seem to grab all the frames available in the video.
🌐
Stack Overflow
stackoverflow.com › questions › 66148138 › opencv-skips-frame
python - Opencv skips frame - Stack Overflow
I am trying to detect objects in opencv but anything I try, the program does not process all the frames. It skips and only ends up showing one or two frames each time. Even if I try something simpl...
🌐
Tam Vu
vuamitom.github.io › 2019 › 12 › 13 › fast-iterate-through-video-frames.html
Fast way to iterate through video frames with Python and OpenCV | Tam Vu
December 13, 2019 - Performance was intolerable. A better alternative would be to skip through frames and only decode the one that we need. Opencv grab and retrieve function can be used for this purpose (which are called by read function internally).
🌐
OpenCV Q&A Forum
answers.opencv.org › question › 81702 › skipping-all-but-the-latest-frame-in-videocapture
Skipping all but the latest frame in VideoCapture - OpenCV Q&A Forum
January 1, 2016 - As an answer to the question "Skipping frames in VideoCapture" Will Stewart presented grap() for skipping frames. But how many frames to I have to skip until I reach the current one? In a loop the frames of a camera are processed using a very time consuming function.
🌐
Packtpub
subscription.packtpub.com › book › data › 9781788474443 › 1 › ch01lvl1sec15 › jumping-between-frames-in-video-files
I/O and GUI | OpenCV 3 Computer Vision with Python Cookbook
In this recipe, you will learn how to position VideoCapture objects at different frame positions. You need to have OpenCV 3.x installed with Python API support.
🌐
OpenCV Q&A Forum
answers.opencv.org › question › 197177 › skip-frames-and-seek-to-end-of-rtsp-stream
Skip frames and seek to end of RTSP stream - OpenCV Q&A Forum
grab() as often as you can. after say, 5 frames you have reached the latest img, probably. retrieve() and process the img only, when desired (e.g. if you're sure, you have the latest) vcap = cv2.VideoCapture("rtsp://{IPcam}/12") ct = 0 while(1): ct += 1 ret = vcap.grab() if ct % 5 == 0: # skip ...