2

I am using OpenCV with python, and more specifically the findTransformECC fonction of cv2 to perform image registration. This function can throw errors if the algorithm does not converge. I catch the error with a simple try ... except instruction, and I handle the error. However the OpenCV error message is still displayed in my terminal, and I would like to hide it. How should I do?

Here is a simple exemple

try:
    cc, warp_matrix = cv2.findTransformECC(img1, img2, warp_matrix)
except cv2.error:
    cc = 15;
    print("An error occured but it does not matter")

If the findTrnaformECC function throws am error my program correctly outputs my custom error message (An error occured but it does not matter) but ALSO the OpenCV error (OpenCV Error: Iterations do not converge (The algorithm stopped before its convergence. The correlation is going to be minimized. Images may be uncorrelated or non-overlapped) in findTransformECC, file /home/travis/miniconda/conda-bld/conda_1485299288502/work/opencv-3.2.0/modules/video/src/ecc.cpp, line 530) and I would like to prevent that.

fonfonx
  • 1,475
  • 21
  • 30
  • 1
    The error is written to `stderr`. So you can just [redirect `stderr`](http://stackoverflow.com/a/6735958/5008845). Or you can tell [opencv to suppress the output](http://stackoverflow.com/a/17575610/5008845), but I'm not aware if there is the Python binding for the `cv::redirectError` function – Miki May 11 '17 at 18:31
  • this seems great but redirecting the standard error did not do anything... – fonfonx May 11 '17 at 19:36
  • Looks like this has been fixed in a later version of OpenCV: with v4.5.3.56, the above approach using `except cv2.error:` is sufficient to catch the exception and the additional output is not written to stderr – 4Oh4 Sep 01 '21 at 09:35

1 Answers1

0

Redirecting stderr did not seem to work but it gave me the idea to redirect it from the command-line which works pretty well (on Unix based systems)

python myscript.py 2> /dev/null

However this will hide all other errors that should be display on stderr. This is not a matter for my precise application but it could be.

fonfonx
  • 1,475
  • 21
  • 30