Skip to content

Commit 52a290e

Browse files
committed
Set default Mat allocator to NumpyAllocator
Fixes #17
1 parent 50f29e5 commit 52a290e

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/core.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,30 @@ using namespace cv;
2828
// exposed, which just runs `return getCoreTlsData().rng`
2929
volatile RNG rng = theRNG();
3030

31+
// Fix for https://github.com/sparkfun/micropython-opencv/issues/17
32+
//
33+
// TLDR; The `StdMatAllocator` gets allocated once, whenever the first time a
34+
// Mat object is created without the NumpyAllocator being set (OpenCV creates
35+
// internal Mat objects for various operations that use whatever the default
36+
// allocator is). Similar to above, the `StdMatAllocator` gets allocated on the
37+
// GC heap, so if a soft reset occurs, the GC gets reset and overwrites the
38+
// memory location, causing problems
39+
//
40+
// Instead of ensuring the `StdMatAllocator` is allocated on the C heap, we just
41+
// set the NumpyAllocator as the default allocator. `Mat::setDefaultAllocator()`
42+
// does not return anything, so this wrapper function returns a dummy value so
43+
// we can use it to initialize a global variable, ensuring it gets run before
44+
// `main()` gets called
45+
bool setNumpyAllocator() {
46+
try {
47+
Mat::setDefaultAllocator(&GetNumpyAllocator());
48+
return true;
49+
} catch (const Exception& e) {
50+
return false;
51+
}
52+
}
53+
volatile bool defaultAllocatorSet = setNumpyAllocator();
54+
3155
mp_obj_t cv2_core_convertScaleAbs(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
3256
// Define the arguments
3357
enum { ARG_src, ARG_dst, ARG_alpha, ARG_beta };

0 commit comments

Comments
 (0)