This question has been posed numerous times on many websites, but not definitive solution. I am trying to run Opencv with a video using function:
import cv2
cap = cv2.VideoCapture('video.mp4')
if(cap.isOpened()==False):
print "Error opening camera"
But it fails every time. I have tried almost all steps from various sites, but couldn't get it to work (including rebuilding ffmpeg separately).
Any help would be much appreciated.
My platform is Ubuntu17 and Python3.
Next, we cay cap = cv2. VideoCapture(0) . This will return video from the first webcam on your computer. If you are watching the tutorial videos, you will see I am using 1, since my first webcam is recording me, and the second webcam is used for the actual tutorial feed. while(True): ret, frame = cap.
cv2. VideoCapture is a function of openCV library(used for computer vision, machine learning, and image processing) which allows working with video either by capturing via live webcam or by a video file.
The VideoCapture class returns a video capture object which we can use to display the video. The class has several methods, for example, there is the get() method which takes a property identifier from cv2.
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.
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.
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.
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.
Lastly, check if the file path is correct or even if the file exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With