In Python OpenCV 2.4.9, when instantiating a VideoWriter object with the usual instruction:
video = cv2.VideoWriter("output.avi", -1, 25, (640,480))
I get the following annoying dialog box that asks me to choose between the various options of compression modalities.
I need to iteratively create VideoWriter objects in order to construct a large video dataset and I am wondering if there is any way to set the compression modality only once and get rid of that dialog box popping up at every new VideoWriter instantiation.
I really need to automate this process, so any help would be truly appreciated
This works smoothly:
video = cv2.VideoWriter("output.avi", 1, 25, (640,480))
My system:
Python 2.7.15
OpenCV 2.4.9
The answer is in the parameter for the constructor of the VideoWriter() . When you pass -1 for the second parameter, that means you re asking for the window to pop up. If you want to choose the codec beforehand, you can do so by setting it to integer corresponding to the given codec.
So the code would look something like this:
# for OCV == 3.X.X
#fourcc = cv2.VideoWriter_fourcc('X', '2', '6', '4')
#for OCV == 2.X.X
fourcc = cv2.cv.FOURCC(*'X264')
video = cv2.VideoWriter("output.avi", fourcc, 25, (640,480))
Related
I am facing a problem in recording a video from camera. I am using python and opencv to do so. I have my images in QImage format, I convert them to numpy array in order to display to stream it when video capturing of the cam (using VideoCapture of opencv), everything works fine.
When I try to record a video and save it in the folder (using VideoWriter_fourcc of opencv), I get no errors but I get an empty video. I did a lot of searching to find the problem but I couldn't.
Here's the code that I use to record a video:
import cv2
fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
#img is a numpy array
videoWriter = cv2.VideoWriter('video.avi', fourcc, 20, (img.shape[0],img.shape[1]))
while True:
videoWriter.write(img)
videoWriter.release()
I tried to change the Framerate, the frameSize, the extension of the video and the code of codec but nothing worked.
I am so desperate. I appreciate all and every help and suggestion I can get.
Thank you
The issue is that you mixed up width and height as you passed them to VideoWriter.
VideoWriter wants (width, height) for the frameSize argument.
Note that width = img.shape[1] and height = img.shape[0]
Giving VideoWriter a, say, 1920x1080 frame to write, while having promised 1080x1920 frames in the constructor, will fail, but silently.
i have a video where the front view of a car was recorded. The file is an .mp4 and i want to process the single images so i can extract more information (Objects, Lane Lines etc.). The problem is, when i want to create a video out of the processed files, i get an error. Here is what i have done so far:
Opened the video with cv2.VideoCapture() - Works fine
Saved the single frames of the video with cv2.imwrite() - Works fine
Creating a video out of single frames with cv2.VideoWriter() - Works fine
Postprocessing the video with cv2.cvtColor(), cv2.GaussianBlur() and cv2.Canny() - Works fine
Creating a video out of the processed images - Does not work.
Here is the code i used:
enter code here
def process_image(image):
gray = functions.grayscale(image)
blur_gray = functions.gaussian_blur(gray, 5)
canny_blur = functions.canny(blur_gray, 100, 200)
return canny_blur
process_on =0
count =0
video= cv2.VideoWriter("output.avi", cv2.VideoWriter_fourcc(*"MJPG"), 10, (1600, 1200))
vidcap = cv2.VideoCapture('input.mp4')
success,image = vidcap.read()
success = True
while success:
processed = process_image(image)
video.write(processed)
This is the error i get:
OpenCV Error: Assertion failed (img.cols == width && img.rows == height*3) in cv::mjpeg::MotionJpegWriter::write, file D:\Build\OpenCV\opencv-3.2.0\modules\videoio\src\cap_mjpeg_encoder.cpp, line 834
Traceback (most recent call last):
File "W:/Roborace/03_Information/10_Data/01_Montreal/camera/right_front_camera/01_Processed/Roborace_CAMERA_create_video.py", line 30, in
video.write(processed)
cv2.error: D:\Build\OpenCV\opencv-3.2.0\modules\videoio\src\cap_mjpeg_encoder.cpp:834: error: (-215) img.cols == width && img.rows == height*3 in function cv::mjpeg::MotionJpegWriter::write
My suggestion is: The normal images have 3 dimensions because of the RGB-color field. The processed images are only having one dimension. How can i adjust this in the cv2.VideoWriter function.
Thanks for your help
The VideoWriter() class only writes color images, not grayscale images unless you are on Windows, which it looks like you might be judging from the paths in your output. On Windows, you can pass the optional argument isColor=0 or isColor=False to the VideoWriter() constructor to write single-channel images. Otherwise, the simple solution is to just stack your grayscale frames into a three-channel image (you can use cv2.merge([gray, gray, gray]) and write that.
From the VideoWriter() docs:
Parameters:
isColor – If it is not zero, the encoder will expect and encode color frames, otherwise it will work with grayscale frames (the flag is currently supported on Windows only).
So by default, isColor=True and the flag cannot be changed on a non-Windows system. So simply doing:
video.write(cv2.merge([processed, processed, processed])
should patch you up. Even though the Windows variant allows writing grayscale frames, it may be better to use this second method for platform independence.
Also as Zindarod mentions in the comments below there are a number of other possible issues with your code here. I'm assuming you've pasted modified code that you weren't actually running here, or that you would have modified otherwise...if that's the case, please only post minimal, complete, and verifiable code examples.
First and foremost, your loop has no end condition, so it's indefinite. Secondly, you're hard-coding the frame size but VideoWriter() does not simply resize the images to that size. You must provide the size of the frame that you will pass into the VideoWriter(). Either resize the frame to the same size before writing to be sure, or create your VideoWriter using the frame size as defined in your VideoCapture() device (using the .get() methods for the frame size properties).
Additionally, you're reading only the first frame outside the loop. Maybe that was intentional, but if you want to process each frame of the video, you'll need to of course read them in a loop, process them, and then write them.
Lastly you should have some better error catching in your code. For e.g., see the OpenCV "Getting Started with Video" Python tutorial. The "Saving a Video" section has the proper checks and balances: run the loop while the video capture device is opened, and process and write the frame only if the frame was read properly; then once it is out of frames, the .read() method will return False, which will allow you to break out of the loop and then close the capture and writer devices. Note the ordering here---the VideoCapture() device will still be "opened" even when you've read the last frame, so you need to close out of the loop by checking the contents of the frame.
Add isColor=False argument to the VideoWriter.
Adjusting VideoWriter this way will solve the issue.
Code:
video= cv2.VideoWriter("output.avi", cv2.VideoWriter_fourcc(*"MJPG"), 10, (1600, 1200), isColor=False)
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
In my project i want to save streaming video.
import cv2;
if __name__ == "__main__":
camera = cv2.VideoCapture(0);
while True:
f,img = camera.read();
cv2.imshow("webcam",img);
if (cv2.waitKey (5) != -1):
break;
`
using above code it is possible to stream video from the web cam. How to write this streaming video to a file?
You can simply save the grabbed frames into images:
camera = cv2.VideoCapture(0)
i = 0
while True:
f,img = camera.read()
cv2.imshow("webcam",img)
if (cv2.waitKey(5) != -1):
break
cv2.imwrite('{0:05d}.jpg'.format(i),img)
i += 1
or to a video like this:
camera = cv2.VideoCapture(0)
video = cv2.VideoWriter('video.avi', -1, 25, (640, 480));
while True:
f,img = camera.read()
video.write(img)
cv2.imshow("webcam",img)
if (cv2.waitKey(5) != -1):
break
video.release()
When creating VideoWriter object, you need to provide several parameters that you can extract from the input stream. A tutorial can be found here.
In ubuntu create video from given pictures using following code
os.system('ffmpeg -f image2 -r 8 -i %05d.bmp -vcodec mpeg4 -y movie3.mp4')
where name of picture is 00000.bmp,00001.bmp,00002.bmp etc..
If you really want to use the codec provided for your pc to compress the frames.
You should set the 2nd parameter of cv2.VideoWriter([filename, fourcc, fps, frameSize[, isColor]]) with the flag value = -1. This will allow you to see a list of codec compress utilized in your pc.
In my case, the codec provided by Intel is named IYUV or I420. I don't know for another manufacturers. fourcc webpage.
Set this information as follow
fourcc = cv2.cv.CV_FOURCC('I','Y','U','V')
# or
fourcc = cv2.cv.CV_FOURCC('I','4','2','0')
# settting all the information
out = cv2.VideoWriter('output1.avi',fourcc, 20, (640,480))
Remember two small parameters which gave me a big headache:
Don't forget the cv2.cv prefix
Introduce the correct frame Size
For everything else, you can use the code provided by Ekalic
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')