Permanent fix for Opencv videocapture

This answer is written with Linux and Python in mind, but the general idea can be applied to any OS and language supported by OpenCV.

The VideoCapture class not opening the video file can have many causes, but the following three applies to most cases.

OpenCV FFMPEG support:

By default OpenCV uses ffmpeg to read video files. OpenCV may not have been built with FFMPEG support. To find out if OpenCV was built with FFMPEG support, in terminal enter:

python -c "import cv2; print(cv2.getBuildInformation())" | grep -i ffmpeg

The output should be something like:

FFMPEG: YES

If the output is No then follow an online guide to build OpenCV from source with ffmpeg support.

FFMPEG Codec:

It’s possible that FFMPEG does not have codec for your specific file. We are going to use this video as an example, to show if FFMPEG has decoding capability for this file.

First, we need to find the encoding format used in this video file. We will be using the mediainfo program. In terminal, enter:

mediainfo video_file.mp4

In the output, under the video heading, look for format. In this case the video encoding used is AVC, which is another name for H264.

pic

Now, we try to find if FFMPEG supports codec for decoding AVC encoded files. In terminal:

ffmpeg -codecs | grep -i avc

On my machine, the output is:

DEV.LS h264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (decoders: h264 h264_crystalhd h264_vdpau ) (encoders: libx264 libx264rgb )

We are interested in DEV, which stands for Decoding, Encoding and Video. This means that AVC is a video encoding format and FFMPEG supports both encoding and decoding capabilities for this format.

File PATH

Lastly, check if the file path is correct or even if the file exists.

Leave a Comment