Write video with opencv with fourcc H264: Cannot load libcuda.so.1 - python

I'm trying to create a video using opencv-python. I have to use H.264 codec for my video so I have the following lines:
import cv2
width = ...
height = ...
name = ...
fourcc = cv2.VideoWriter_fourcc(*'H264')
self.video = cv2.VideoWriter(name, fourcc, 30, (width, height))
When I run the code I get the following error:
[h264_nvenc # 0x562490d62d80] Cannot load libcuda.so.1
Could not open codec 'h264_nvenc': Unspecified error
As I see in the error, I need libcuda.so.1 library which comes with nvidia driver afaik, but my laptop has no dedicated graphic card.
Is it possible to write a video using H.264 using my laptop? If yes, please advice how. Thank you!

Related

cv2.VideoWriter() file format .mp4 with HEVC codec

I am using cv2.VideoWriter() to record from a single camera and writing the video to a .mp4 file with a HEVC codec. I had this script previously working on a (Windows) laptop with the following code:
video = cv2.VideoCapture(0)
frame_width = int(video.get(3))
frame_height = int(video.get(4))
# create output file
out1 = cv2.VideoWriter(videoFileName, cv2.VideoWriter_fourcc(str('H'), str('E'), str('V'), str('C')), 30.0,
(frame_width, frame_height))
I am setting up the script on a new laptop and the above code no longer records and throws the following error:
OpenCV: FFMPEG: tag 0x43564548/'HEVC' is not supported with codec id 173 and format 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x31766568/'hev1'
[hevc_mf # 0000028eed319d00] COM must not be in STA mode
[ERROR:0] global /build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp (2794) open Could not open codec hevc_mf, error: Unspecified error
[ERROR:0] global /build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp (2811) open VIDEOIO/FFMPEG: Failed to initialize VideoWriter
I have read through many forums who suggest that this is not possible with cv2 because it does not support the HEVC codec. I have also read the .mp4 and HEVC are possibly not compatible. However, it was previously functioning on the other laptop. Therefore, I know it works in some manner. Note: I did not set it up initially on the other laptop.
I have also tried
# fourcc = cv2.VideoWriter_fourcc(*'mp4v')
# fourcc = cv2.VideoWriter_fourcc(*'h264')
# out1 = cv2.VideoWriter(videoFileName, fourcc, 30.0, (frame_width, frame_height))
with mp4v working but not the codec I initially had and h264 throwing an error similar to above.
Has anyone encountered a solution to this problem?
Additional info:
Windows 10, Python 3.8.10 through Pycharm, cv2 installed via opencv-python and imported with ´from cv2 import cv2`

Python OpenCV video format play in browser

I'm trying to create a video from a sequence of images and display it in a browser but from some weird reason no matter what codec or file format I use I get the following error:
No video with supported format and mime type found
Here is my code:
ready_images = []
import cv2
for img in videos['Images']:
image = cv2.imread(img.fileName)
ready_images.append(image)
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
video_name = videos['Images'][0].gifLocationPath + "//" + videos['Name']
frame = cv2.imread(videos['Images'][0].fileName)
height, width, layers = frame.shape
video_name = video_name[:-4]+".mp4"
video = cv2.VideoWriter(video_name, fourcc, 20.0, (width, height))
for image in ready_images:
video.write(image)
cv2.destroyAllWindows()
video.release()
The funny thing is that in Firefox or Chrome the videos are not working but in Edge... they actually work.
I don't want to use FFMPEG and would prefer to make it work with OpenCV.
If any of you guys know what format of video (I know the web formats are webm, ogg, mp4) or codec I should use for this, please, just let me know.
Thanks.
MP4V or MPEG-4 part 2 is not supported by most browsers, you may want to try H.264 (MPEG-4 part 10) instead.
To do that, change:
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
to
fourcc = cv2.VideoWriter_fourcc(*'H264')
If you are using Python 3, use the following hexadecimal code instead (there seems to be a bug when using the four bytes notation):
fourcc = 0x00000021
Run the script and you will likely get the following error message:
Failed to load OpenH264 library: openh264-1.6.0-win32msvc.dll
Please check environment and/or download library: https://github.com/cisco/openh264/releases
You need to do as the message says and download the required library from github and place it somewhere accessible by your PATH.
Using H.264 compression you will also get a smaller file which is better for Web.
I know the question is old but for everyone that is looking for a compatible codec + container for web browser :
VP8 or VP80 is a compatible encoder
cv2.VideoWriter_fourcc('V','P','8','0')
I used it with .webM as a container.
Native WebM support by Mozilla Firefox,[7][8] Opera,[9][10] and Google Chrome[11] was announced at the 2010 Google I/O conference
https://en.wikipedia.org/wiki/WebM
it worked like a charm and with pretty good performance even though
for some reason I got this error when creating videoWriter objects :
OpenCV: FFMPEG: tag 0x30385056/'VP80' is not supported with codec id 139 and format 'webm / WebM'
Get .webm suffix audio file.
fourcc = cv2.VideoWriter_fourcc(*'vp80')
video_writer = cv2.VideoWriter('file.webm', fourcc, 20, (640, 480))
In html:
<body>
<video width="320" height="240" controls>
<source src="file.webm" type="video/webm">
</video>
</body>
It works on centos7 and Windows10.
I print the all available mp4 codecs by fourcc=-1.
After that I check codecs which are useful for me. I see there avc1.
So I write the code like:
fourcc = cv2.VideoWriter_fourcc(*'avc1')
When print the codes, you also see they are lowercase.

Can't write and save a video file using OpenCV and Python

I'm trying to process frames from a video stream, and it as a new video.
This is what I'm doing :
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('Videos/output.mp4',fourcc, fps, (1080,1080))
I keep getting :
OpenCV: FFMPEG: tag 0x44495658/'XVID' is not supported with codec id 13 and format 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x00000020/' ???'
I think I'm using the wrong fourcc value... Which one should I use ? I've been trying a lot of them.
I'm using Ubuntu 16.04, Python 2.7.11 and OpenCV 3.1.0
Define the codec and create VideoWriter object like this
fourcc = cv2.VideoWriter_fourcc(*'MPEG')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
For Windows users
I am using OpenCV 2 with Python 3.6, on Windows 10.
The 'XVID' codec, along with producing a .avi file, seems to be the most generic solution (if not the only one that works).
fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter('test.avi', fourcc, 60, (320, 240))
In addition, only BGR can be directly written with such a VideoWriter declaration. Don't try to write gray frames: the output would be empty.
The problem that you are having is that you are trying to export the frames in XVID format but the name of your output file is ending with .mp4. You should change the export format to MP4V or the name of your output file to .avi.
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
out = cv2.VideoWriter('Videos/output.mp4',fourcc, fps, (1080,1080))
alternative
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('Videos/output.avi',fourcc, fps, (1080,1080))
here you can find more information about the video codecs
The size of the frame(width,height) you are giving, should match the size of the frame you want to save.
so
fw = int(cap.get(3))
fh = int(cap.get(4))
print("w,h",fw,fh)
out = cv2.VideoWriter('fb1.avi',cv2.VideoWriter_fourcc('X','V','I','D'), fps, (fw,fh))
If you want to save video by opencv in mp4 format, let
Follow this link:
you should replace:
fourcc = cv2.VideoWriter_fourcc(*'XVID')
by:
fourcc = cv2.VideoWriter_fourcc(*'FMP4')
I tried and succeeded.
I had the same problem. With me, it turned out that I had switched the height and width of the video, so the frame dimensions did not match the video specifications and as a result nothing was written. Make sure they match exactly.
Also, OpenCV seems to give that same warning if the file extension does not match the codec used. Specifically, it wants .avi for the XVID codec.
I wanted to save as a .mp4, and using *"mp4v" turned out to be the right code, on Linux at least.
Check the example below
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
video = cv2.VideoWriter('output.mp4', fourcc, fps, (width, height))
Install K-Lite Mega Codec Pack: https://filehippo.com/download_klite_mega_codec/
This error occurs because some codecs are not available by default in Windows media player. So by installing this software, the video works fine with same code.
If you are using linux try this
fourcc = 0x00000021
out = cv2.VideoWriter('Videos/output.mp4',fourcc, fps, (1080,1080))
In my case, i use:
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
video = cv2.VideoWriter(video_name, fourcc, FPS, (width,height))
and this work :>
On a mac
writer = cv2.VideoWriter('mysupervideo.mp4', cv2.VideoWriter.fourcc(*'mp4v'), 20, (width, height))
Works better

Unable to write video using python and opencv2 on mac os x

I am using mac os x 1.7.5 with python 2.7.5_1 and opencv 2.4.4_0 installed via macports. I seem to have all the latest dependent ports.
In my code, the cv2.Videowriter() is successfully created and opened which produces a 6kb .avi file but videoFile.write(img0) doesn't write anything into that file. I really am not able to figure out why the video stream isn't written to the file. Any insights?
My code is as follows:
import cv2
import cv
cv2.namedWindow("Original")
cap0 = cv2.VideoCapture(0)
codec = cv.CV_FOURCC('D','I','V','X')
print codec
videoFile = cv2.VideoWriter();
videoFile.open('video.avi', codec, 25, (640, 480),1)
key = -1
while(key < 0):
success0, img0 = cap0.read()
cv2.imshow("Original", img0)
videoFile.write(img0)
key = cv2.waitKey(1)
cv2.destroyAllWindows()
I've tried these codecs and none of them worked: I420, AVC1, YUV1, PIM1, MJPG, MP42, MP4V, DIV3, DIVX, XVID, IUYV,FFV1, FLV1, U263, H264, ZLIB
I've also gone through all the quick time codecs mentioned here
Using ZLIB codec I get the error:
[zlib # 0x7fb0d130a000] Specified pixel format yuv420p is invalid or not supported
Using H264 codec I get an error:
[libx264 # 0x7fe423869600] broken ffmpeg default settings detected
[libx264 # 0x7fe423869600] use an encoding preset (e.g. -vpre medium)
[libx264 # 0x7fe423869600] preset usage: -vpre <speed> -vpre <profile>
[libx264 # 0x7fe423869600] speed presets are listed in x264 --help
[libx264 # 0x7fe423869600] profile is optional; x264 defaults to high
I didn't understand what the above errors meant. I tried reinstalling ffmpeg to the latest version (1.2.2_0+gpl2) but my script still doesn't work. All the other codecs did not give any error.
I've even tried the file extensions of .mpg and .mkv with the above codecs. Sometimes I would get an error saying that the codec was not suitable for the file extension but when I didn't get error I would simply get the unreadable video file of a minuscule size.
Any help is much appreciated.
ps: I've already gone through the following SO questions which didn't solve my issue:
using opencv2 write streaming video in python
Writing video with OpenCV + Python + Mac
Create an avi video with opencv and python on a mac
Python OpenCV, can't write a video (.avi) to file
Creating AVI files in OpenCV
read/write avi video on MAC using openCV
Python OpenCV 2.4 writes half-complete PNG video frames
The problem seems to have been with the image size in the function videoFile.open('video.avi', codec, 25, (640, 480),1)
So I updated my script to include
size = (int(cap0.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)),
int(cap0.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)))
And then accordingly changed videoFile.open to
videoFile.open('video.avi', codec, 25, size,1)
Then my script started working.
I've tried the codecs with fourcc: IYUV, I420, PIM1, MJPG, FFV1 and DIVX with file extension .avi
Each of the above codec worked with frame rates 16, 20, 25 and 30 except for PIM1 which seems to work only on 20fps and above.
Also,
Codec with fourcc THEO worked with file extension .ogv
XVID worked properly with file extension .mkv and though the .mkv container should work with any encoding I got a variety of weird results with other codecs.
FLV1 with file extension .flv didn't work. It gave the error:
[flv # 0x7f8414006000] Tag FLV1/0x31564c46 incompatible with output codec id '22' ([2][0][0][0])
FLV4 with file extension .flv didn't give an error but opencv's videowrite outputted an error "Could not update video file"
Of the codecs that worked with .avi file container, DIVX produced the smallest video file (~4Mb for 4 sec video) and IYUV produced the largest file (~160Mb for 4 sec video)
Note:
fps = videoCapture.get(cv2.cv.CV_CAP_PROP_FPS) always returns 0.0 when capturing from webcam. It is a bug in OpenCV2.4.3 and OpenCV2.4.4
I also found out that ffmpeg cannot grab images from Mac's iSight and FacetimeHD webcams the way it can from Windows and Ubuntu because designers at Apple have prohibited easy access to the mac's camera... what a shame!
References:
http://en.wikipedia.org/wiki/Comparison_of_container_formats
Initially I was getting a 0kb video file. I changed the Codec from MJPG to iYUV. It worked for me. Python 2.7 and openCV 2.4.5.
cap = cv2.VideoCapture(0)
fourCC = cv2.cv.CV_FOURCC('i','Y','U', 'V'); # Important to notice cv2.cv.CV_FOURCC
size = (int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)))
out = cv2.VideoWriter("Test.avi", fourCC, 15.0, size, True)
To get h264 working, install ffmpeg from the following link. Its quite a cumbersome installation but it ll get the encoder up and running.
https://trac.ffmpeg.org/wiki/CompilationGuide/Ubuntu

Python OpenCV2 cv2.cv_fourcc not working with VideoWriter

As the title states, when I run the cv2.videowriter function I get 'module' object has no attribute CV_FOURCC.
Code:
# Creates a video file from webcam stream
import cv2
Create test window
cv2.namedWindow("cam_out", cv2.CV_WINDOW_AUTOSIZE)
# Create vid cap object
vid = cv2.VideoCapture(1)
# Create video writer object
vidwrite = cv2.VideoWriter(['testvideo', cv2.CV_FOURCC('M','J','P','G'), 25,
(640,480),True])
Kind of late to the party, but if anyone needs it for newer versions of opencv2, then the command is:
cv2.VideoWriter_fourcc(c1, c2, c3, c4)
Change cv2.CV_FOURCC('M','J','P','G') to cv2.cv.CV_FOURCC('M','J','P','G').
For OpenCV 3 do this:
cv2.VideoWriter_fourcc(*'MJPG')
credit #SiffgyF
With OpenCV 3:
# Create video writer object
vidwrite = cv2.VideoWriter('testvideo.avi', cv2.VideoWriter_fourcc(*'XVID'), 25,
(640,480),True)
you can find the sample at "opencv_install_dir\sources\doc\py_tutorials\py_gui\py_video_display\py_video_display.markdown"
ps: I can't find any description with 'cv2.VideoWriter_fourcc(...)' in official documentation.
From experience, if on OSX, this is what worked for me when writing out to mp4 files:
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
if you want to write to Mp4 file just use this codec it's for 2020 opencv4.2 and plus
fourcc = cv2.VideoWriter_fourcc(*'X264')
video_writer = cv2.VideoWriter('outeringe.mp4', fourcc, 20, (640, 480))
use x264 instead of MP4V
I've the same error (on macos ) in opencv-python 4.2.0.32
upgrading to opencv-python-4.4.0.46 solve it , without any need for code changes
I use this code:
fourcc = cv2.CV_FOURCC(*'XVID')

Categories