Itseez/opencv — pull request #776 by virtuald (2013-04-05 04:51:23+00:00)
Title: Catch exceptions when large allocations fail

When using static PyObject* pyopencv_from(const Mat& m) (cv2.cpp:374), on line 382 the m.copyTo call may fail if the allocation is too large, and a C++ exception is thrown. If this exception is not handled, the process crashes on Windows.

A good example of this happening is in the imread wrapper, when I tried to open a 30MB JPEG file repeatedly. After calling cv::imread wrapped with ERRWRAP2(), it returns the result of pyopencv_from()... which is not wrapped, and the exception goes uncaught. Oddly enough, sometimes the allocation fails in cv::imread, but many times it fails outside of it... thus the crash.

I *think* the proper way to handle this is to surround line 382 with ERRWRAP2(). I tested this with my 30MB JPEG file, and it no longer crashes. It now reports that it cannot allocate the memory and throws a python exception in the python code (which is the expected behavior). That is what this pull request does.

However, I note that there are a number of places where the return value of pyopencv_from is passed to other python functions (like Py_BuildValue). I'm not sure, but I *think* it's ok to pass a NULL to those functions, and the error will be bubbled up correctly. This patch seems to work for me, however.