Can't write and save a video file using OpenCV and Python - 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

Related

writing a video without any loss in data or bitrate - opencv (python)

I am trying to write a video file without any loss in OpenCV, but so far any codec that I have selected from fourcc codec lists somehow results in loss of data.
regarding the recording parameters I am using:
fps = int(cap.get(cv2.CAP_PROP_FPS))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
used these codecs so far but they either to compression or upsize video bit rate
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
fourcc = cv2.VideoWriter_fourcc(*'RGBA')
fourcc = cv2.VideoWriter_fourcc(*'x265')
fourcc = cv2.VideoWriter_fourcc('H','2','6','4')
my video writer function is:
writer= cv2.VideoWriter(out_dest, fourcc, fps, (width,height))
Just to be clear, I do not want any sort of compression for the output video.
I also use
vid_format = int(cap.get(cv2.CAP_PROP_FOURCC))
to get the output video bit rate and compare it to the original video.
I also found someone on GitHub using skvideo but wasn't able to perform the same code
https://gist.github.com/docPhil99/a612c355cd31e69a0d3a6d2f87bfde8b
as it kept showing an extension error and couldn't find proper documentation on how to use it!
Thank you in advance
An Update on the topic:
the final output writer codec will be used as the video writer for BGR to RGB conversion in OpenCV, if you have any other ideas or suggestions that can do the job, I'm all ears!
If all you need to do is to get RGB data out of raw AVI file and feed the RGB frame data with MediaPipe, there is no need for intermediate file to store RGB data because FFmpeg can convert the pixel format on the fly by specifying output -pix_fmt rgb24 option.
To do this, you can try my ffmpegio package to load the data. My package is designed for your use case to remove the need to set up FFmpeg call. To install:
pip install ffmpegio
You also need FFmpeg in the system.
Then video.read() loads the video data:
import ffmpegio
fs, I = ffmpegio.video.read('datafile.avi',pix_fmt='rgb24')
# fs = framerate
# I = 250x480x640x3 numpy array containing RGB video data
If you don't want to read all 250 frames at once, you can use the stream interface to work on X number of frames at a time:
with ffmpegio.open('datafile.avi','rv', blocksize=25, pix_fmt='rgb24') as f:
for I in f: # loops 10 times, 25 frames at a time
# I = 25x480x640x3 numpy array

List all supported codecs/fourcc tags on Raspberry Pi 4 using python, opencv

This is my code for recording videos on Raspberry Pi 4 running Raspbian Buster:
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
writer = cv2.VideoWriter(tempVideo.path, fourcc, framerate, resolution, True)
writer.write(frame)
However, no matter what codec I try, I keep getting errors like:
OpenCV: FFMPEG: tag 0x47504a4d/'MJPG' is not supported with codec id 7 and format 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v'
Setting fourcc = 1 also did not help. Here is what I see:
OpenCV: FFMPEG: tag 0xffffffff/'????' is not found (format 'mp4 / MP4 (MPEG-4 Part 14)'
Is there a way to list all the supported codecs and their tags?
Here is the link with all fourcc codecs.
http://www.fourcc.org/codecs.php
Some codecs don't exist there, but in your case, it is not an error it is just a fallback, so your code is running anyway and in the output you will get your mp4 file.
If you don't like how it looks just use this
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
or
fourcc = 0x00000021
It's not an exact answer to the question, but what eventually helped me is cv2.getBuildInformation() is an answer. It shows what video formats are supported by particular build of opencv.

OpenCV Video Write-out Size is Reduced

I am trying to combine frames into a video using openCV, using the following codes. However, the total size of frames in png format is over 500 megabytes, yet the output video is only 360 kilobytes.
How can I write out the video without any compression?
#setting fourcc
fourcc = cv2.VideoWriter_fourcc(*'XVID')
#creating the writer object
writer=cv2.VideoWriter('Screen1.avi', fourcc, 30, (unitWidth, unitHeight), True)
#writing out the frames into video
for i in range(Frames):
img=cv2.imread('./Screen1/frame'+str(i)+'.png')
writer.write(img)
writer.release()
If you are worrying about video quality, try a lossless codec like the Huffman Lossless Codec.
fourcc = cv2.VideoWriter_fourcc(*'HFYU')
Or search for any other lossless codec.
If you want absolutely no compression at all, you can try fourcc = 0, which will output every frame raw and result in very large file size.

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.

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