OpenCV videowrite doesn't write video
Asked Answered
F

21

39

I used the following page from OpenCV 3.0.0 tutorial: Tutorial in docs

When I tried to use the example that saves videos, it doesn't work.

It displays the content from the webcam, and also creates a file called output.avi, but when I checked the size of ouput.avi, it was zero bytes.

I also tried using different codecs, like YUY2.

I use Python 2.7.8 and OpenCV 3.0.0 and Windows 8.1

Fiscal answered 28/3, 2015 at 18:31 Comment(1)
If anyone has a similar issue and is writing black and white image, you need to specify that the image is not in colour: out = cv2.VideoWriter('output.avi',fourcc, 20.0,(int(cap.get(3)),int(cap.get(4))), False)Orelie
A
40

I had the same problem and I solved it by specifying the video output resolution to exactly the same as input:

cap = cv2.VideoCapture('vtest.avi')
...
out = cv2.VideoWriter('output.avi',fourcc, 20.0,(int(cap.get(3)),int(cap.get(4))))

Of course make sure you got ffmpeg installed and working.

Alonsoalonzo answered 29/8, 2017 at 8:18 Comment(1)
Even if the input is from converted PIL image, make sure the size is the same!Adjutant
T
30

I was struggling with this problem for a few hours then I realized that I had typed the image's shape wrong.

It is (width, height), ie:

(image.shape[1], image.shape[0])

and not

(image.shape[0], image.shape[1])

This is how my working code looks like finally... (I am on a Windows machine):

video_path = FILENAME + '.avi'
size = images[0].shape[1], images[0].shape[0] ## <<<--- NOTICE THIS
video = cv2.VideoWriter(video_path,cv2.VideoWriter_fourcc(*'DIVX'), 60, size)  

for img in images:  
    video.write(img)

cv2.destroyAllWindows()
video.close()
Transversal answered 24/6, 2020 at 2:38 Comment(2)
Thank you so much. For me the problem is, that just DIVX as fourcc works.Flameout
Thanks for this. I wish OpenCV raised an exception when it got a frame that didn't match the dims. That would have saved me a lot of time.Milford
V
22

Replacing:

fourcc = cv2.VideoWriter_fourcc(*'XVID')

With:

fourcc = cv2.VideoWriter_fourcc('M','J','P','G')

Worked for me...

More generally:

Look up the fourcc code of the video compression format you're after here, and whatever the code is - for instance 'FMP4' for FFMpeg - plug it in in the following manner:

cv2.VideoWriter_fourcc('F','M','P','4')
Vietnam answered 6/1, 2016 at 0:52 Comment(3)
Actually, (*'XVID') is the same as ('X', 'V', 'I', 'D') Take a look at docs.python.org/dev/tutorial/…Ethelstan
Yes, cv2.VideoWriter_fourcc('M','J','P','G') is work. I use opencv 4.Brew
Link is broken.Pompom
L
9

Make sure you are using the correct fourcc 4-byte code. The example on the tutorial has:

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

This XVID code may only work for linux. The documentation above the example states (in the tutorial): "In Windows: DIVX (More to be tested and added)." So if you haven't, try replacing the fourcc line above with:

fourcc = cv2.VideoWriter_fourcc(*'DIVX')

I use cv2.VideoWriter on linux quite often and it always works. So if the above doesn't work you can always try it on a linux vm.

Linotype answered 29/3, 2015 at 2:19 Comment(5)
Unfortunately, I cannot get it to work. DIVX doesn't work for me. Thanks for helping.Fiscal
CV2 makes use of ffmpeg. It could be that cv2 is not finding the application.Linotype
I looked through my code and found that I have this line: fourcc = cv2.cv.CV_FOURCC('X', 'V', 'I', 'D'). This is for a Linux vm but you could make appropriate changes and try it. I don't know where I originally found this code but it works for me.Linotype
It doesn't work on Linux, Debian Stretch stable. If yes for you, then you are a lucky man. For me it has created the output file once properly, once with 0 bytes length and 500-times no file was created (no error reported; command timing as if all works excellent) :(((Compressive
@Compressive I just tested it on ubuntu 16.04 with opencv3 installed and it is working for me. I tested with color image frames so as posted above I don't specify the isColor flag, however you may want to verify that you have this correctly set to True/False, as needed. This won't give an exception if you have it set incorrectly, you just get an "un-playable" video. If this doesn't help it may be that you need to install ffmpeg or alternative on your machine.Linotype
M
7

In my case, I thought the codec was an obstacle but it wasn't. Instead, adjusting the dimensions being consumed by videoWriter() did the trick:

(ok, frame) = cv2.VideoCapture(videoPath).read()

 fourcc = cv2.VideoWriter_fourcc(*'XVID')
 out = cv2.VideoWriter(output, fourcc, 10.0, (1280, 720))

(1280,720) was used because frame.shape from my video outputs (1280, 720, 3). It made avi to mp4 and vice versa possible. Didn't have to worry about reconciling the codec.

Macklin answered 15/5, 2018 at 3:38 Comment(0)
D
7

Check the resolution of your images! I was trying with odd-shaped images (1284x709) and ended up with unreadable videos of 1k in size. After resizing my image to the closest 'common' resolution: image = cv2.resize(image, (1280,720)), it worked just fine.

Derange answered 15/3, 2019 at 22:22 Comment(1)
Also, check for an error message. I had on my jupyter notebook: OpenCV: FFMPEG: tag 0x5634504d/'MP4V' is not supported with codec id 13 and format 'mp4 / MP4 (MPEG-4 Part 14)' OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v', and by using the exact 4 letters as suggested (mp4v), respecting the case, the message disappeared.Derange
M
5

I suspect there are a lot of reasons video writing fails silently, and in my case, my frame was a composite of a 3 channel image and a 4 channel image (transparent overlay). Converting the end result to BGR format as follows allowed the video to save successfully.

width = 1280
height = 720
FPS = 30
fourcc = VideoWriter_fourcc(*'avc1')
video = VideoWriter('output.mp4', fourcc, float(FPS), (width, height))
for img in images:
  frame = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
  video.write(frame)
video.release()
Monogenesis answered 19/11, 2020 at 21:18 Comment(0)
G
3

It should be a problem with the codec you're using.

Have you tried:

cv.CV_FOURCC('i', 'Y', 'U', 'V')

This one worked for me.

Gallenz answered 8/12, 2015 at 6:22 Comment(0)
G
2

On windows 7 and using Python 2.7 and OpenCV 2.4.8, I experienced the fact that if the file NAME is "output.mpg" would not write.

I solved it by changing to "output.avi".

Gorge answered 21/2, 2018 at 4:33 Comment(0)
L
2

I have the exact same issue. I am using OpenCV in C++, but I believe you can still pass -1 instead of choosing the codec so you can have a drop down menu of the available codecs even in python. From there I tried all different codecs and just like Leonard Zhou, the IYUV codec was the one that worked for me. Also note that it was the only one that worked even though I could use XVID just fine on another machine with the same code and same codec installer.

EDIT: What I suggested worked as a patch, the main issue was solved on my end by adding the opencv_ffmpeg dll in the executable's folder.

Lucerne answered 20/8, 2018 at 18:45 Comment(0)
U
1

I changed the Video writer size to my screen resolution size and it worked.

here is the solution.

out = cv2.VideoWriter("output.avi", fourcc, 5.0, (1920, 1080))
Ugaritic answered 10/8, 2018 at 7:7 Comment(0)
R
1

It worked for me after I assigned the actual frame size and not what I thought the size was:

ret, frame = cap.read()
height, width, channels = frame.shape
codec = cv2.VideoWriter_fourcc(*"DIVX")
out=cv2.VideoWriter('new.avi',codec ,20.0,(width, height))

And put out.write(frame) inside the while loop before cv2.imshow("Frame", frame).

Rosenwald answered 26/12, 2020 at 17:54 Comment(1)
On my system, only 'DIVX' works whereas the encoding on the opencv documentation examples, 'M', 'J', 'P', 'G', just silently writes no file. I wish there was a way to verify the codec so that my code is more safely portable.Haunted
F
1

After trying hours to find the error, I finally found it. So here are some things to keep in mind. (For Linux users particularly)

  1. Use this codec ("MJPG").

    cv2.VideoWriter_fourcc(*'MJPG')
    
  2. Do not forget to write the Boolean value as final argument (True for RGB and False for GrayScale) in

    cv2.VideoWriter(path, fourcc, float(frameRate), frameSize, True)
    
  3. The argument, frameSize required by cv2.VideoWriter is a tuple of form (width, height) and not (height, width) which is the shape of image array if you open the image using cv2.read or Image.open. So don't forget to invert it.

Flin answered 15/6, 2022 at 11:41 Comment(0)
S
0

To state the obvious, make sure you're giving not only a correct path, but also a video name. i.e. path/'video.avi' and not just path/. It will fail silently otherwise.

Slone answered 22/6, 2021 at 10:26 Comment(0)
B
0

In my case I am resizing the image, but saving video with original size instead of new size.

Benevento answered 4/1, 2022 at 14:54 Comment(0)
O
0

The above methods work only for RGB frames/images. Incase you are trying to write a grayscale image, pass a parameter 0 to the VideoWriter():

fourcc = cv2.VideoWriter_fourcc(*"MJPG")
out = cv2.VideoWriter('output.avi', fourcc, 30, size, 0)
Outhaul answered 16/2, 2022 at 15:43 Comment(0)
U
0

I had same issue that the video file was being created without any errors but it won't run and had a size of few KBs. Here's how I resolved it;

  1. Make sure you have passed FPS argument in float value.
  2. The output resolution needs to be same as of input video resolution.
Unifoliolate answered 5/3, 2022 at 15:50 Comment(0)
B
0

In my case, the folder did not exists. It fails silently .

os.makedirs(os.path.dirname(self.video_output_path_temp), exist_ok=True)
out = cv2.VideoWriter(self.video_output_path_temp, fourcc, frame_rate, (screen_width, screen_height))

Brigand answered 29/9, 2023 at 3:28 Comment(0)
P
0

Install ffmpeg using

conda install -c conda-forge ffmpeg
Piselli answered 7/11, 2023 at 12:6 Comment(0)
C
0

I had a similar problem on macOS Sonoma (14.1) and OpenCV 4.9 (in Python), but in my case the writer was not outputting because the directory (file path) I had specified did not exist.

I assumed that VideoWriter would create the directory, but found out that I needed to create the directory first before VideoWriter would write to it.

Cholecalciferol answered 24/4 at 20:26 Comment(0)
S
-2

I tried by creating its exe using pyinstaller Recorder.py it worked for me.

Remember before using pyinstaller you have to pip install pyinstaller.

Snip answered 5/1, 2021 at 14:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.