Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV runs out of memory when reading video file

This example of reading video from file with cv2.VideoCapture in python OpenCV runs out of memory:

import cv2
cap = cv2.VideoCapture('file.mp4')
while True:
    ret, frame = cap.read()

It takes ~300 frames at 1920x1080 before it runs out. Tested in both OpenCV 3.0.0 beta and 2.4.8, running in latest Pythonxy on Windows 7 64-bit.

What needs to be added to this code to make it not run out of memory but rather free each frame before reading the next frame?

like image 661
Alex I Avatar asked Jan 08 '14 07:01

Alex I


People also ask

Can OpenCV read video?

VideoCapture) To read a video with OpenCV, we can use the cv2. VideoCapture(filename, apiPreference) class. In the case where you want to read a video from a file, the first argument is the path to the video file (eg: my_videos/test_video.

What video formats can OpenCV read?

The MPEG format 480p version is more than enough to demonstrate the basic capabilities of OpenCV's video processing. Note that OpenCV supports reading and writing several popular formats (such as AVI and MPEG).

What does cv2 VideoCapture 0 mean?

Next, we cay cap = cv2. VideoCapture(0) . This will return video from the first webcam on your computer.


Video Answer


2 Answers

You can use scikit-image which has a video loader and supports Opencv and Gstreamer backends as per documentation. I have never used Gstreamer.

import cv2
from skimage.io import Video

cap = Video(videofile)
fc = cap.frame_count()
for i in np.arange(fc):
   z = cap.get_index_frame(i)

Now use the frame z for whatever you want to do!

like image 166
Ashish Avatar answered Nov 03 '22 10:11

Ashish


Try

while True:
    ret, frame = cap.read()
    if(!frame)
        break;

to make sure the frame is valid to avoid reading frames forever even not valid.

like image 32
herohuyongtao Avatar answered Nov 03 '22 11:11

herohuyongtao