title: How to capture messages written to stderr by OpenCV?
body: <p>In case of invalid parameters, <code>cv2.VideoWriter</code> writes stuff to stderr. here is a minimal example:</p>
  <pre class="lang-py prettyprint-override"><code>import cv2
  
  cv2.VideoWriter(&quot;foo.mp4&quot;, cv2.VideoWriter_fourcc(*&quot;mp4v&quot;), 90000, (240, 240))
  </code></pre>
  <p>Running like so</p>
  <pre class="lang-sh prettyprint-override"><code>python3 video_verification/verification.py 2&gt; err.txt
  </code></pre>
  <p>one can see the expected errors in <code>err.txt</code>:</p>
  <pre><code>[mpeg4 @ 0x13e4640] timebase 1/90000 not supported by MPEG 4 standard, the maximum admitted value for the timebase denominator is 65535
  [ERROR:0] global /tmp/pip-req-build-13uokl4r/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp (2705) open Could not open codec mpeg4, error: Unspecified error
  [ERROR:0] global /tmp/pip-req-build-13uokl4r/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp (2722) open VIDEOIO/FFMPEG: Failed to initialize VideoWriter
  </code></pre>
  <p>However, I'm unable to capture this directly in Python. Here are my two (failing) attemps so far:</p>
  <pre class="lang-py prettyprint-override"><code>import io
  from contextlib import redirect_stdout, redirect_stderr
  
  import cv2
  
  f_out = io.StringIO()
  f_err = io.StringIO()
  with redirect_stdout(f_out):
      with redirect_stderr(f_err):
          fps = 90000
          writer = cv2.VideoWriter(
              &quot;foo.mp4&quot;, cv2.VideoWriter_fourcc(*&quot;mp4v&quot;),
              fps, (240, 240)
          )
  
  print(f&quot;stdout: {f_out.getvalue()}&quot;)
  print(f&quot;stderr: {f_err.getvalue()}&quot;)
  </code></pre>
  <pre class="lang-py prettyprint-override"><code>import io
  import sys
  
  import cv2
  
  
  def flush():
      sys.stdout.flush()
      sys.stderr.flush()
  
  
  flush()
  
  original_stdout = sys.stdout
  original_stderr = sys.stderr
  
  captured_stdout = io.StringIO()
  captured_stderr = io.StringIO()
  
  sys.stdout = captured_stdout
  sys.stderr = captured_stderr
  
  flush()
  
  cv2.VideoWriter(&quot;foo.mp4&quot;, cv2.VideoWriter_fourcc(*&quot;mp4v&quot;), 90000, (240, 240))
  
  flush()
  
  sys.stdout = original_stdout
  sys.stderr = original_stderr
  
  print(f&quot;stdout: {captured_stdout.getvalue()}&quot;)
  print(f&quot;stderr: {captured_stderr.getvalue()}&quot;)
  </code></pre>
  <p>I would love to learn what I'm doing wrong. :-)</p>