1 From b0281a5c844ea0b0d9e0104674474adf50810f49 Mon Sep 17 00:00:00 2001
2 From: BrutusTT <brutusthetschiepel@gmail.com>
3 Date: Wed, 4 Sep 2019 11:39:30 +0100
4 Subject: [PATCH 1/2] add OpenCV4 support addresses
5 ros-perception/vision_opencv#272
8 cv_bridge/CMakeLists.txt | 2 +-
9 cv_bridge/src/CMakeLists.txt | 8 +++++---
10 2 files changed, 6 insertions(+), 4 deletions(-)
12 diff --git a/cv_bridge/CMakeLists.txt b/cv_bridge/CMakeLists.txt
13 index 997bef3e..c203aad1 100644
14 --- a/cv_bridge/CMakeLists.txt
15 +++ b/cv_bridge/CMakeLists.txt
16 @@ -13,7 +13,7 @@ if(NOT ANDROID)
18 find_package(Boost REQUIRED)
20 -find_package(OpenCV 3 REQUIRED
21 +find_package(OpenCV REQUIRED
25 diff --git a/cv_bridge/src/CMakeLists.txt b/cv_bridge/src/CMakeLists.txt
26 index 37ba30ee..6d91003b 100644
27 --- a/cv_bridge/src/CMakeLists.txt
28 +++ b/cv_bridge/src/CMakeLists.txt
29 @@ -32,10 +32,12 @@ if (PYTHON_VERSION_MAJOR VERSION_EQUAL 3)
30 add_definitions(-DPYTHON3)
33 -if (OpenCV_VERSION_MAJOR VERSION_EQUAL 3)
34 -add_library(${PROJECT_NAME}_boost module.cpp module_opencv3.cpp)
35 +if (OpenCV_VERSION_MAJOR VERSION_EQUAL 4)
36 + add_library(${PROJECT_NAME}_boost module.cpp module_opencv4.cpp)
37 +elseif(OpenCV_VERSION_MAJOR VERSION_EQUAL 3)
38 + add_library(${PROJECT_NAME}_boost module.cpp module_opencv3.cpp)
40 -add_library(${PROJECT_NAME}_boost module.cpp module_opencv2.cpp)
41 + add_library(${PROJECT_NAME}_boost module.cpp module_opencv2.cpp)
43 target_link_libraries(${PROJECT_NAME}_boost ${Boost_LIBRARIES}
46 From 8e01b44c5c1c0003dc91273076f8ca7feb9a8025 Mon Sep 17 00:00:00 2001
47 From: BrutusTT <brutusthetschiepel@gmail.com>
48 Date: Thu, 17 Oct 2019 14:37:40 +0100
49 Subject: [PATCH 2/2] added missig file
52 cv_bridge/src/module_opencv4.cpp | 371 +++++++++++++++++++++++++++++++
53 1 file changed, 371 insertions(+)
54 create mode 100644 cv_bridge/src/module_opencv4.cpp
56 diff --git a/cv_bridge/src/module_opencv4.cpp b/cv_bridge/src/module_opencv4.cpp
58 index 00000000..60a9d05d
60 +++ b/cv_bridge/src/module_opencv4.cpp
62 +// Taken from opencv/modules/python/src2/cv2.cpp
64 +#include "module.hpp"
66 +#include "opencv2/core/types_c.h"
68 +#include "opencv2/opencv_modules.hpp"
70 +#include "pycompat.hpp"
72 +static PyObject* opencv_error = 0;
74 +static int failmsg(const char *fmt, ...)
80 + vsnprintf(str, sizeof(str), fmt, ap);
83 + PyErr_SetString(PyExc_TypeError, str);
91 + // more fields may be added if necessary
93 + ArgInfo(const char * name_, bool outputarg_)
95 + , outputarg(outputarg_) {}
97 + // to match with older pyopencv_to function signature
98 + operator const char *() const { return name; }
101 +class PyAllowThreads
104 + PyAllowThreads() : _state(PyEval_SaveThread()) {}
107 + PyEval_RestoreThread(_state);
110 + PyThreadState* _state;
116 + PyEnsureGIL() : _state(PyGILState_Ensure()) {}
119 + PyGILState_Release(_state);
122 + PyGILState_STATE _state;
125 +#define ERRWRAP2(expr) \
128 + PyAllowThreads allowThreads; \
131 +catch (const cv::Exception &e) \
133 + PyErr_SetString(opencv_error, e.what()); \
139 +static PyObject* failmsgp(const char *fmt, ...)
145 + vsnprintf(str, sizeof(str), fmt, ap);
148 + PyErr_SetString(PyExc_TypeError, str);
152 +class NumpyAllocator : public MatAllocator
155 + NumpyAllocator() { stdAllocator = Mat::getStdAllocator(); }
156 + ~NumpyAllocator() {}
158 + UMatData* allocate(PyObject* o, int dims, const int* sizes, int type, size_t* step) const
160 + UMatData* u = new UMatData(this);
161 + u->data = u->origdata = (uchar*)PyArray_DATA((PyArrayObject*) o);
162 + npy_intp* _strides = PyArray_STRIDES((PyArrayObject*) o);
163 + for( int i = 0; i < dims - 1; i++ )
164 + step[i] = (size_t)_strides[i];
165 + step[dims-1] = CV_ELEM_SIZE(type);
166 + u->size = sizes[0]*step[0];
171 + UMatData* allocate(int dims0, const int* sizes, int type, void* data, size_t* step, AccessFlag flags, UMatUsageFlags usageFlags) const
175 + CV_Error(Error::StsAssert, "The data should normally be NULL!");
176 + // probably this is safe to do in such extreme case
177 + return stdAllocator->allocate(dims0, sizes, type, data, step, flags, usageFlags);
181 + int depth = CV_MAT_DEPTH(type);
182 + int cn = CV_MAT_CN(type);
183 + const int f = (int)(sizeof(size_t)/8);
184 + int typenum = depth == CV_8U ? NPY_UBYTE : depth == CV_8S ? NPY_BYTE :
185 + depth == CV_16U ? NPY_USHORT : depth == CV_16S ? NPY_SHORT :
186 + depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT :
187 + depth == CV_64F ? NPY_DOUBLE : f*NPY_ULONGLONG + (f^1)*NPY_UINT;
188 + int i, dims = dims0;
189 + cv::AutoBuffer<npy_intp> _sizes(dims + 1);
190 + for( i = 0; i < dims; i++ )
191 + _sizes[i] = sizes[i];
193 + _sizes[dims++] = cn;
194 + PyObject* o = PyArray_SimpleNew(dims, _sizes.data(), typenum);
196 + CV_Error_(Error::StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims));
197 + return allocate(o, dims0, sizes, type, step);
200 + bool allocate(UMatData* u, AccessFlag accessFlags, UMatUsageFlags usageFlags) const CV_OVERRIDE
202 + return stdAllocator->allocate(u, accessFlags, usageFlags);
205 + void deallocate(UMatData* u) const CV_OVERRIDE
210 + CV_Assert(u->urefcount >= 0);
211 + CV_Assert(u->refcount >= 0);
212 + if(u->refcount == 0)
214 + PyObject* o = (PyObject*)u->userdata;
220 + const MatAllocator* stdAllocator;
223 +NumpyAllocator g_numpyAllocator;
226 +template<typename T> static
227 +bool pyopencv_to(PyObject* obj, T& p, const char* name = "<unknown>");
229 +template<typename T> static
230 +PyObject* pyopencv_from(const T& src);
232 +enum { ARG_NONE = 0, ARG_MAT = 1, ARG_SCALAR = 2 };
234 +// special case, when the convertor needs full ArgInfo structure
235 +static bool pyopencv_to(PyObject* o, Mat& m, const ArgInfo info)
237 + // to avoid PyArray_Check() to crash even with valid array
238 + do_numpy_import( );
241 + bool allowND = true;
242 + if(!o || o == Py_None)
245 + m.allocator = &g_numpyAllocator;
249 + if( PyInt_Check(o) )
251 + double v[] = {(double)PyInt_AsLong((PyObject*)o), 0., 0., 0.};
252 + m = Mat(4, 1, CV_64F, v).clone();
255 + if( PyFloat_Check(o) )
257 + double v[] = {PyFloat_AsDouble((PyObject*)o), 0., 0., 0.};
258 + m = Mat(4, 1, CV_64F, v).clone();
261 + if( PyTuple_Check(o) )
263 + int i, sz = (int)PyTuple_Size((PyObject*)o);
264 + m = Mat(sz, 1, CV_64F);
265 + for( i = 0; i < sz; i++ )
267 + PyObject* oi = PyTuple_GET_ITEM(o, i);
268 + if( PyInt_Check(oi) )
269 + m.at<double>(i) = (double)PyInt_AsLong(oi);
270 + else if( PyFloat_Check(oi) )
271 + m.at<double>(i) = (double)PyFloat_AsDouble(oi);
274 + failmsg("%s is not a numerical tuple", info.name);
282 + if( !PyArray_Check(o) )
284 + failmsg("%s is not a numpy array, neither a scalar", info.name);
288 + PyArrayObject* oarr = (PyArrayObject*) o;
290 + bool needcopy = false, needcast = false;
291 + int typenum = PyArray_TYPE(oarr), new_typenum = typenum;
292 + int type = typenum == NPY_UBYTE ? CV_8U :
293 + typenum == NPY_BYTE ? CV_8S :
294 + typenum == NPY_USHORT ? CV_16U :
295 + typenum == NPY_SHORT ? CV_16S :
296 + typenum == NPY_INT ? CV_32S :
297 + typenum == NPY_INT32 ? CV_32S :
298 + typenum == NPY_FLOAT ? CV_32F :
299 + typenum == NPY_DOUBLE ? CV_64F : -1;
303 + if( typenum == NPY_INT64 || typenum == NPY_UINT64 || type == NPY_LONG )
305 + needcopy = needcast = true;
306 + new_typenum = NPY_INT;
311 + failmsg("%s data type = %d is not supported", info.name, typenum);
317 + const int CV_MAX_DIM = 32;
320 + int ndims = PyArray_NDIM(oarr);
321 + if(ndims >= CV_MAX_DIM)
323 + failmsg("%s dimensionality (=%d) is too high", info.name, ndims);
327 + int size[CV_MAX_DIM+1];
328 + size_t step[CV_MAX_DIM+1];
329 + size_t elemsize = CV_ELEM_SIZE1(type);
330 + const npy_intp* _sizes = PyArray_DIMS(oarr);
331 + const npy_intp* _strides = PyArray_STRIDES(oarr);
332 + bool ismultichannel = ndims == 3 && _sizes[2] <= CV_CN_MAX;
334 + for( int i = ndims-1; i >= 0 && !needcopy; i-- )
336 + // these checks handle cases of
337 + // a) multi-dimensional (ndims > 2) arrays, as well as simpler 1- and 2-dimensional cases
338 + // b) transposed arrays, where _strides[] elements go in non-descending order
339 + // c) flipped arrays, where some of _strides[] elements are negative
340 + if( (i == ndims-1 && (size_t)_strides[i] != elemsize) ||
341 + (i < ndims-1 && _strides[i] < _strides[i+1]) )
345 + if( ismultichannel && _strides[1] != (npy_intp)elemsize*_sizes[2] )
350 + if (info.outputarg)
352 + failmsg("Layout of the output array %s is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)", info.name);
357 + o = PyArray_Cast(oarr, new_typenum);
358 + oarr = (PyArrayObject*) o;
361 + oarr = PyArray_GETCONTIGUOUS(oarr);
362 + o = (PyObject*) oarr;
365 + _strides = PyArray_STRIDES(oarr);
368 + for(int i = 0; i < ndims; i++)
370 + size[i] = (int)_sizes[i];
371 + step[i] = (size_t)_strides[i];
374 + // handle degenerate case
377 + step[ndims] = elemsize;
381 + if( ismultichannel )
384 + type |= CV_MAKETYPE(0, size[2]);
387 + if( ndims > 2 && !allowND )
389 + failmsg("%s has more than 2 dimensions", info.name);
393 + m = Mat(ndims, size, type, PyArray_DATA(oarr), step);
394 + m.u = g_numpyAllocator.allocate(o, ndims, size, type, step);
401 + m.allocator = &g_numpyAllocator;
407 +bool pyopencv_to(PyObject* o, Mat& m, const char* name)
409 + return pyopencv_to(o, m, ArgInfo(name, 0));
412 +PyObject* pyopencv_from(const Mat& m)
416 + Mat temp, *p = (Mat*)&m;
417 + if(!p->u || p->allocator != &g_numpyAllocator)
419 + temp.allocator = &g_numpyAllocator;
420 + ERRWRAP2(m.copyTo(temp));
423 + PyObject* o = (PyObject*)p->u->userdata;
428 +int convert_to_CvMat2(const PyObject* o, cv::Mat& m)
430 + pyopencv_to(const_cast<PyObject*>(o), m, "unknown");