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
🌐
OpenCV Q&A Forum
answers.opencv.org › question › 24714 › skipping-frames-in-videocapture
Skipping frames in VideoCapture - OpenCV Q&A Forum
Again, assuming you are using VideoCapture in HighGUI, you can do set the CAP_PROP_POS_FRAMES property before grabbing/reading the frames. That way the next frame to be read will be from that frame onwards. ... Using this method you can set the CV_CAP_PROP_POS_FRAMES property to the frame number ...
Discussions

VideoCapture.read() skipped frames?
System information (version) OpenCV => 2.13 Operating System / Platform => Linux2.6.32 el6 x86_64 Compiler => gcc 4.4.7 Python => 2.6.6 Detailed description I use python to read all the frames from a video file. But I found some frames a... More on github.com
🌐 github.com
4
November 1, 2016
`cv2.VideoCapture().grab()` skips frames with .webm videos
System information (version) OpenCV => 4.5.1 Operating System / Platform => MacOS 10.14.6 Compiler => clang++ (ver 9.1.0.9020039) Detailed description I'm using cv2 and pafy to do work on streamed ... More on github.com
🌐 github.com
April 16, 2021
python - Does Cap.read() skip frames in camera stream but not when running from file? - Stack Overflow
i noticed a behaviour that i didn't find an answer for in the documentation. when I capture a stream from camera using VideoCapture(0), check code below I noticed that some frames are skipped becau... More on stackoverflow.com
🌐 stackoverflow.com
September 29, 2020
python - How to skip missing images/frames within an image sequence when used with cv2.videocapture()? - Stack Overflow
I have around 40K frames stored in a directory. I am using following code to read them and eventually write them in a video file. The following snippet is just for displaying the video. cap = cv2. More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
github.com › opencv › opencv › issues › 7592
VideoCapture.read() skipped frames? · Issue #7592 · opencv/opencv
November 1, 2016 - But I found some frames are skipped using VideoCapture.read(). as well as using VideoCapture.set(cv.CV_CAP_PROP_POS_FRAMES, frame_no) Here is the bug case. http://www.miaopai.com/show/9wzVbYXrGO3qHsxcIVMbqQ__.htm I use read method to extract frames numbering from 3353 to 3359. Also I use set method to get the 3357 and 3358 frame. The bug is the 3353 frame extracted by former method is the same as 3357 frame extracted by later method, and so is 3359 to 3358. cap = cv2.VideoCapture(videofile) while True: frame_no = int(cap.get(cv.CV_CAP_PROP_POS_FRAMES)) succ, frame = cap.read() if not succ: break print frame_no ·
Author: opencv
🌐
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
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. I've tested this with the following code: import cv2 frame_count = 0 filename = 'Test 1.avi' # load video file cap = cv2.VideoCapture(str(filename)) # find fps of video file fps = cap.get(cv2.CAP_PROP_FPS) spf = 1/fps print "Frames per second using cap.get(cv2.CAP_PROP_FPS) : {0}".format(fps) print "Seconds per frame using 1/fps :", spf while(cap.isOpened()): ret, frame = cap.read() frame_count = frame_count + 1 if ret == False: break print 'Number of Frames:', frame_count, cap.get(cv2.CAP_PROP_FRAME_COUNT) cap.release()
🌐
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 - # naive version cap = cv2.VideoCapture(video_path) success, img = cap.read() fno = 0 while success: if fno % sample_rate == 0: do_something(img) # read next frame success, img = cap.read() However, each call to cap.read() would result in unnecessary decoding of frames to be discarded. Performance was intolerable. A better alternative would be to skip through frames and only decode the one that we need.
🌐
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 ...
Find elsewhere
🌐
Funvisiontutorials
funvisiontutorials.com › home › opencv tutorial, videocapture playback, frame skip
Funvision opencv C++ tutorials: Opencv tutorial, VideoCapture playback, frame skip
In this example, I want to access GOPRO HD faster and skip frames of video, and in memory is pure fantasy over minute video length.
🌐
Stack Overflow
stackoverflow.com › questions › 64119834 › does-cap-read-skip-frames-in-camera-stream-but-not-when-running-from-file
python - Does Cap.read() skip frames in camera stream but not when running from file? - Stack Overflow
September 29, 2020 - when I capture a stream from camera using VideoCapture(0), check code below I noticed that some frames are skipped because of the delay I put in the code. but when I playback a video, it doesn't skip the frames. Copycap = cv2.VideoCapture(0) #cap = cv2.VideoCapture("awesomevideo.mp4") while True : # Get a new frame from camera retval, frame = cap.read() time.sleep(1) # Display images cv2.imshow("frame", frame) am I understanding this behaviour correctly, or it's an issue with my code?
🌐
Stack Overflow
stackoverflow.com › questions › 63247244 › how-to-skip-missing-images-frames-within-an-image-sequence-when-used-with-cv2-vi
python - How to skip missing images/frames within an image sequence when used with cv2.videocapture()? - Stack Overflow
I have around 40K frames stored in a directory. I am using following code to read them and eventually write them in a video file. The following snippet is just for displaying the video. cap = cv2.VideoCapture('path/to/images/0d.jpg') while(True): ret, frame = cap.read() if (ret == True): cv2.imshow('video output', frame) cv2.waitKey(30)
🌐
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
🌐
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()
🌐
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 ...
🌐
Reddit
reddit.com › r/opencv › [question] is there a way to only load/use the middle section of a video?
r/opencv on Reddit: [Question] Is there a way to only load/use the middle section of a video?
June 22, 2023 -

I have a lot of long video samples (1-2 minutes) I've been using to test some computer vision code on, but the real-world use case would be taking in live image data over a couple seconds. Is there a way to take only a few seconds of video from the middle of one of the long videos? I can't just take frames from the start of the video since the phenomena I'm trying to analyze doesn't start till a while into the video.

I probably could brute force it by just going through the first section of frames without doing any analysis on them but I'd prefer a more elegant solution if there is one.

Edit: I should specify I'm using Python

🌐
Quora
quora.com › How-do-I-decrease-the-frames-per-second-in-OpenCV-python
How to decrease the frames per second in OpenCV python - Quora
Calculate skip factor = round(camera_fps / target_fps) and drop frames accordingly. ... Use cap.set(cv2.CAP_PROP_FPS, target_fps).
🌐
OpenCV
forum.opencv.org › python
Help with optimization opencv videocapture optical flow analysis - Python - OpenCV
March 28, 2024 - Hello, I am now using python opencv in docker to analyse video files. There are about 24 files of 1 hour on which i do movement analysis with nvidia optical flow. However it takes about 40 minutes to analyze one day (24 hours, so 24 files of 1 hour). I would like this to speed up, i now do the processing in parralel en my cpu is 100% because of the reading of the video files i think.
🌐
Reddit
reddit.com › r/opencv › [question] how do i get a fresh frame taken after calling cv.videocapture.read ?
r/opencv on Reddit: [Question] How do I get a fresh frame taken AFTER calling cv.VideoCapture.read ?
August 14, 2021 -

I'm reading a frame from a usb webcam, but I need the frame to be guaranteed to be taken by the camera after I request it. Unfortunately, I get the last buffed frame. What I'm doing now is calling read twice, once to flush the buffer, and once to wait for and get another image. This works pretty well but seems to fail 2% of the time or so, and cuts my frame rate in half (under ideal circumstances it would be slower but not by that much if I'm thinking clearly). I just don't understand what it's actually doing. How do I make sure to get the next available frame that wasn't taken before I called cv.VideoCapture.read ?

Top answer
1 of 2
1
Do a search for CAP_PROP_BUFFERSIZE. You want to set this to 1. For example: https://stackoverflow.com/a/63057626/13022
2 of 2
1
There are two possibilities here: Reduce the frame buffer length to 1, so you can only ever have the latest frame (unfortunately not always obvious or even possible to do, and sometimes costs framerate (e.g. achieving it by only requesting stills when you need them isn’t always a viable solution if you want to stream and process video)) grab frames repeatedly in the background at faster than the video framerate and then only retrieve the latest frame when you need your next one If you’re using Python you can do option 2 with the Camera class of my library pythonic-cv , which uses a thread for grabbing frames and provides an iterator that retrieves just the latest frame when you need it/ask for it. If you’re not using python then you can set up your own thread for that, or if you know how long your processing tends to take you can potentially add grabs at multiple points throughout, which is likely easier to set up when starting out but harder to maintain as you change your processing or add extra functionality around it. Edit: as a note, a read in OpenCV is just a grab followed by a retrieve, which is often convenient if you need to view/process every frame that you get. It’s useful to split out the calls if you don’t need some of the frames (grab just says “I want a frame”, retrieve actually decides it into an array of pixels in memory), or if you’re doing things where the timing of when each image is taken needs to be precise relative to something else (e.g. for a stereo camera setup you want both images taken at exactly the same time, so don’t want to decode one before starting to take the next one)
🌐
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 - VideoCapture camera(0); Mat frame; while(true) { camera.read(frame); imshow("window", frame); waitKey(); } I put something in front of the camera and counted how many frames it took until it appeared on the screen, then took it away and did the same. Turns out in my case there are exactly 5 frames buffered.
🌐
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 - skip n raw frame datas (just update related pointer or status?) file_path = "sample.mp4" cap = cv2.VideoCapture(file_path) cap.skip(9999) ret, frame = cap.read() if ret: cv2.imwrite("10000thFrame.jpg", frame) cap.release()
Author: opencv