In embedding development using pure C, we usually pre-allocate a continuous memory before executing cv algorithm, and don’t allocate new memory in runtime (execpt little temp variables on stack) for better memory management and less memory fragments (too many memory fragments may cause longger address time and especially cause crash under JNI due to delayed GC). A simple code is like below:
struct Image
{
...
};
struct ObjectDetection
{
...
};
bool InitObjectDetection(void** p)
{
*p = malloc(0x1000);
Image* ip = (Image*)*p;
ip->width = 0;
...
ObjectDetection* op = (ObjectDetection*)*p+sizeof(Image);
op->networdStucture = ...;
return true;
}
bool ExecuteObjectDetection(void* p)
{
...
}
void FreeObjectDetection(void* p)
{
free(p);
p = nullptr;
}
int main()
{
void* p = nullptr;
InitObjectDetection(&p);
ExecuteObjectDetection(p);
FreeObjectDetection(p);
return 0;
}
Now let’s turn to modern C++, is there any way to do the same thing with OpenCV? cv::Mat seems auto allocate and free memory when created and destructed and we cannot specify the memory address, is there any way to let it ALL happen in a pre-allocated memory?