# Write to list of VideoWriter objects

**URL:** <https://forum.opencv.org/t/write-to-list-of-videowriter-objects/1924>\
**Category:** Python\
**Tags:** videowriter\
**Created:** [March 3, 2021, 1:49am UTC](https://forum.opencv.org/t/write-to-list-of-videowriter-objects/1924 "2021-03-03T01:49:40Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![alex\_h](https://avatars.discourse-cdn.com/v4/letter/a/3e96dc/32.png) [@alex\_h](https://forum.opencv.org/u/alex_h)\
**Post date:** [March 3, 2021, 1:49am UTC](https://forum.opencv.org/t/write-to-list-of-videowriter-objects/1924/1 "2021-03-03T01:49:40Z")

</div>

Hi,

I have a recording setup with several different webcams (the number of which may change from day to day). I am trying to write a program in Python that allows me passing a list of input videos from a txt file, open all videos and process the video feeds SIMULTANEOUSLY, but save them SEPARATELY into different video files.

The code I have works great so far, but I am getting stuck in one particular question:  
Is there a way of creating a list of VideoWriter objects and write to them in turns, calling them via an index?

Opening several videos via iteration works like a charm (‘cam\_name’ is the list of my camera IDs, i.e. 0, 1, 2, … ):

> cap = [cv2.VideoCapture(i) for i in cam\_name]

Even creating a list of VideoWriter objects works without problems (and all videos start appearing under the file paths passed by the list ‘outnames’):

> outfile = [cv2.VideoWriter(i,cv2.VideoWriter\_fourcc(‘M’, ‘J’, ‘P’, ‘G’),30,(640, 480)) for i in [item for item in outnames]]

However, within my while loop, I seem to not be able to call the ‘.write’ function of these VideoWriter objects from my list using an iterator (here, ‘i’ is an integer indicating the position in ‘outfile’ I want to address, and ‘frame’ is the image I’d like to stich to the video):

> outfile[i].write(frame)

I double-checked each step in the code and the problem definitely appears in ‘outfile[i].write’. Notably, the code runs through without error! It just seems like ‘write’ isn’t doing anything. The video files created with ‘cv2.VideoWriter’ remain unmodified while my loop is running through.  
If I use an ‘imwrite’ workaround, I manage to save the single frames and later stich them together into videos with e.g. ffmpeg, but I’d like to avoid that and call the VideoWriter objects in my loop.

Hope someone can help me! Thanks!

PS: If someone knows the solution in C++, it would also help 🙂

---

<div class="post-metadata">

**Author:** ![alex\_h](https://avatars.discourse-cdn.com/v4/letter/a/3e96dc/32.png) [@alex\_h](https://forum.opencv.org/u/alex_h)\
**Post date:** [March 3, 2021, 9:30am UTC](https://forum.opencv.org/t/write-to-list-of-videowriter-objects/1924/2 "2021-03-03T09:30:37Z")

</div>

UPDATE: I also tried now solving this with the “exec()” function of Python, passing the command as string. Again, this works when creating the videos, but not when trying to write to them.

> strexe = str(“vid” + str(i) + " = cv2.VideoWriter(‘" + str([item for item in outnames][i]) + "’, cv2.VideoWriter\_fourcc(‘M’, ‘J’, ‘P’, ‘G’), " + 30 + “, (” + str(640) + ", " + str(height) + “))”)  
> exec(strexe)

> strexe = str(“vid” + str(i) + “.write(crop\_img)”)  
> eval(strexe)

It also seems that “write” is not supporting the “exec” function.

> exec(‘print(dir())’)

Can I somehow add ‘write’ to the exec dictionary?

Otherwise I’ll have to use many if-clauses to make the code stable for potentially creating tens of output videos 😛

---

<div class="post-metadata">

**Author:** ![crackwitz](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/crackwitz/32/14_2.png) [@crackwitz](https://forum.opencv.org/u/crackwitz)\
**Post date:** [March 3, 2021, 11:00am UTC](https://forum.opencv.org/t/write-to-list-of-videowriter-objects/1924/3 "2021-03-03T11:00:14Z")

</div>

welcome!

> [@alex\_h](#):
>
> I seem to not be able to

post your error message and the lines of code around where the exception is thrown.

actually, reduce your code to the bare minimum that reproduces the issue, but is still runnable. then post that.

> [@alex\_h](#):
>
> solving this with the “exec()” function of Python

**do not** do that. don’t just try things. you have to figure out **why** something failed. **then** you can decide if you can fix it, or try something else. and do not use `exec()`. please don’t.

---

<div class="post-metadata">

**Author:** ![alex\_h](https://avatars.discourse-cdn.com/v4/letter/a/3e96dc/32.png) [@alex\_h](https://forum.opencv.org/u/alex_h)\
**Post date:** [March 3, 2021, 12:51pm UTC](https://forum.opencv.org/t/write-to-list-of-videowriter-objects/1924/4 "2021-03-03T12:51:39Z")

</div>

It was a stupid mistake I made!! I found it. In my code, I am cutting out rectangular areas from the videos and saving them to new video files.  
When setting up the video writer, I calculated width and height for VideoWriter as

> width = x\_max - x\_min + 1  
> height = y\_max - y\_min + 1

… (where x\_min, x\_max, y\_min and y\_max are the corner of the rectangle), but to my surprise the ‘+1’ messes things up here. It’s still not entirely clear to me why e.g. following image:  
x x x x  
x x x x  
x x x x  
Should have a width of 3 and a height of 2? But maybe my understanding of the maths behind picture manipulation is not good enough.

Anyway, my whole question concerning VideoWriter is hence obsolete. The code works now flawlessly (with the iteration solution from the main question, but also the exec() solution from my comment above - however, I agree, exec() is suboptimal). Do you want me to delete my question or clarify in the main text what the solution was??

I would suggest to the developers that ‘.write’ should throw an error if the height and width of the frame one wants to append is different from the settings in VideoWriter! My code never threw an error, the produced video files were just empty. I read in other forums that people had similar problems: Their code would run without error, but in fact some settings in VideoWriter were not matching with frames they wanted to append.

Thanks again for the help and sorry for the confusion!

---

<div class="post-metadata">

**Author:** ![crackwitz](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/crackwitz/32/14_2.png) [@crackwitz](https://forum.opencv.org/u/crackwitz)\
**Post date:** [March 3, 2021, 3:21pm UTC](https://forum.opencv.org/t/write-to-list-of-videowriter-objects/1924/5 "2021-03-03T15:21:46Z")

</div>

> [@alex\_h](#):
>
> following image:  
> x x x x  
> x x x x  
> x x x x  
> Should have a width of 3 and a height of 2?

it shouldn’t? your calculations are wrong.

width = xmax - xmin  
height = ymax - ymin  
subregion = big\_picture[ymin:ymax, xmin:xmax]

that’s all there is to it. that is just numpy.

yes, if argument to write() has different size from what was initialized, throwing an error would be a good idea. you should open an issue on github about that.

---

<div class="post-metadata">

**Author:** ![alex\_h](https://avatars.discourse-cdn.com/v4/letter/a/3e96dc/32.png) [@alex\_h](https://forum.opencv.org/u/alex_h)\
**Post date:** [March 3, 2021, 4:59pm UTC](https://forum.opencv.org/t/write-to-list-of-videowriter-objects/1924/6 "2021-03-03T16:59:25Z")

</div>

Oh yes, my bad. Always running into the same problem with indexing in Python (being used to R). Managed to get my head around indices starting at 0, but it’s still super weird to me that ‘0:3’ means 0,1,2.

I have a list of pixels I want to extract, e.g.

> x\_from\_to = [0,3]  
> y\_from\_to = [0,2]

So to get cropped area of 4x3 I have to do:

> frame\_small = frame[y\_from\_to[0]:(y\_from\_to[1]+1), x\_from\_to[0]:(x\_from\_to[1]+1)]

Concerning VideoWriter.write() I created an issue on Github:

> <https://github.com/opencv/opencv/issues/19670>
>
> \<!--
> If you have a question rather than reporting a bug please go to https://fo…rum.opencv.org where you get much faster responses.
> If you need further assistance please read \[How To Contribute\](https://github.com/opencv/opencv/wiki/How\_to\_contribute).
> 
> This is a template helping you to create an issue which can be processed as quickly as possible. This is the bug reporting section for the OpenCV library.
> \--\>
> 
> \##### System information (version)
> \<!-- Example
> \- OpenCV =\> 4.2
> \- Operating System / Platform =\> Windows 64 Bit
> \- Compiler =\> Visual Studio 2017
> \--\>
> 
> \- OpenCV =\> 4.5.0-dev
> \- Operating System / Platform =\> Windows 64 Bit
> \- Compiler =\> Python 3.9.0 \[MSC v.1927 64 bit (AMD64)\]
> 
> \##### Detailed description
> 
> I have now struggled with this in two independent projects. I was processing video files and changing width and height of the frames. Then I wrote them to a new video with VideoWriter.write(). The code never threw an error, however, only an empty video file came out. I spent hours of code checking before I found out that the frame I was appending to the new video had one pixel less in width and height.
> Hence, my suggestion: Could you let VideoWriter.write() throw an error if the dimensions of the frame to append don't match the video you want to create? I saw in some forums that other people had the same problem. I think it will help us a lot debugging our code :)
> 
> \##### Steps to reproduce
> 
> \`\`\`
> import cv2
> import numpy as np
> \# Create image to append
> img\_to\_append = np.zeros(\[99,99,3\])
> \# Open VideoWriter
> out1 = cv2.VideoWriter('test1.avi', cv2.VideoWriter\_fourcc('M','J','P','G'), 2, (99,99))
> out2 = cv2.VideoWriter('test2.avi', cv2.VideoWriter\_fourcc('M','J','P','G'), 2, (100,100))
> \# Append frame 100 times (neither throws an error!, but out1 becomes an actual video and out2 does not)
> for i in range(0,100):
> out1.write(img\_to\_append)
> out2.write(img\_to\_append)
> 
> \# Release videos
> out1.release()
> out2.release()
> 
> \`\`\`
> 
> \<!-- to add code example fence it with triple backticks and optional file extension
> \`\`\`.cpp
> // C++ code example
> \`\`\`
> or attach as .txt or .zip file
> \--\>
> 
> \##### Issue submission checklist
> 
> - \[\] I report the issue, it's not a question
> \<!--
> OpenCV team works with forum.opencv.org, Stack Overflow and other communities
> to discuss problems. Tickets with question without real issue statement will be
> closed.
> --\>
> - \[\] I checked the problem with documentation, FAQ, open issues,
> forum.opencv.org, Stack Overflow, etc and have not found solution
> \<!--
> Places to check:
> \* OpenCV documentation: https://docs.opencv.org
> \* FAQ page: https://github.com/opencv/opencv/wiki/FAQ
> \* OpenCV forum: https://forum.opencv.org
> \* OpenCV issue tracker: https://github.com/opencv/opencv/issues?q=is%3Aissue
> \* Stack Overflow branch: https://stackoverflow.com/questions/tagged/opencv
> --\>
> - \[\] I updated to latest OpenCV version and the issue is still there
> \<!--
> master branch for OpenCV 4.x and 3.4 branch for OpenCV 3.x releases.
> OpenCV team supports only latest release for each branch.
> The ticket is closed, if the problem is not reproduced with modern version.
> --\>
> - \[\] There is reproducer code and related data files: videos, images, onnx, etc
> \<!--
> The best reproducer -- test case for OpenCV that we can add to the library.
> Recommendations for media files and binary files:
> \* Try to reproduce the issue with images and videos in opencv\_extra repository
> to reduce attachment size
> \* Use PNG for images, if you report some CV related bug, but not image reader
> issue
> \* Attach the image as archive to the ticket, if you report some reader issue.
> Image hosting services compress images and it breaks the repro code.
> \* Provide ONNX file for some public model or ONNX file with with random weights,
> if you report ONNX parsing or handling issue. Architecture details diagram
> from netron tool can be very useful too. See https://lutzroeder.github.io/netron/
> --\>
