The Python Oracle

How can I use OpenCV (Python) to read a video file WITHOUT looping (Mac OS)?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Darkness Approaches Looping

--

Chapters
00:00 How Can I Use Opencv (Python) To Read A Video File Without Looping (Mac Os)?
02:05 Accepted Answer Score 2
02:42 Thank you

--

Full question
https://stackoverflow.com/questions/1670...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #opencv

#avk47



ACCEPTED ANSWER

Score 2


Don't forget to add a check if the video file has been successfully opened.

if( !cam.isOpened() )
  throw "Error when reading image file";

Grab frames by piping them into a cv::Mat in your loop

Mat frame;

for( ; ; )
{
    cam >> frame;
    if(!frame)
        break;
    imshow("w", frame);
    waitKey(20);
}

The loop should terminate correctly after frame is false.

In order to also terminate the loop exactly you could do

cam.get(CV_CAP_PROP_FRAME_COUNT)

to get the exact number of frames. Getting the video without loop is not possible as its read in increments. You could wrap this into a separate function though.