将CV :: MAT实例存储在C 中的堆上
Store cv::Mat instance on Heap in C++
这不是仅相关的openCV,而是一般的C 问题。
我想在方法中加载图像并使用指针将其存储在堆上。
这是我当前正在使用的方法的代码:
int load_offline_image(std::string src, unsigned char* buffer, int* width, int* height, int* len) {
if (offline_image) {
delete offline_image;
}
offline_image = new cv::Mat(cv::imread(src, cv::IMREAD_GRAYSCALE));
if (offline_image->data == 0){
return ERROR;
}
int numRow = offline_image->rows;
int numCol = offline_image->cols;
*len = numCol*numRow*offline_image->elemSize1();
*width = offline_image->size().width;
*height = offline_image->size().height;
buffer = offline_image->data;
return OK;
}
方法内部一切正常。但是,当我尝试从外部访问buffer
变量时,它是Null
。我敢肯定,问题与指针offline_image
指向cv::Mat
实例的事实有关,该实例仅存在于堆栈上,并且在执行load_offline_image
完成后,该实例的地址丢失了。
btw: offline_image
是一个全局变量。
在C 中实现此操作的正确方法是什么,因此我为cv::Mat
实例分配堆空间?
您可能想要的是这样的东西:
int load_offline_image(std::string src, unsigned char** buffer, int* width, int* height, int* len) {
...
*buffer = offline_image->data;
....
}
这个原因是 - 您想更改buffer
指向的地址。使用unsigned char* buffer
更改地址,但更改仅限于调用方法。您需要一个unsigned char**
才能更改以超越方法。
另外,我建议您考虑步幅宽度 - 这可能与图像宽度不同。您可以查询offline_image.isContinuous()
来弄清楚这一点。
另一个注意事项,这不是使用cv::Mat
的合适方法。同样,尚不清楚谁是责任是要清除buffer
指向的内存。这是一种更清洁的方法:
int main() {
// Calling application
buffer = new unsigned char[width*height*dims];
...
load_offline_image(..., buffer, width, height, ...);
...
delete[] buffer;
}
int load_offline_image(...) {
Mat offline_image;
// use imread
// Copy the buffer over
memcpy(buffer, offline_image->data, ...);
// Since we're using the Mat structure, the Mat will be deallocated automatically
}
这将两个函数分开,让他们分别管理记忆。
相关文章:
- 将字符串存储在c++中的稳定内存中
- std::原子加载和存储都需要吗
- C++:将控制台输出存储在宏中更好吗
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 使用QProcess执行命令,并将结果存储在QStringList中
- 访问存储在向量C++中的结构的多态成员
- 如何从存储在std::映射中的std::集中删除元素
- 概念中的cv限定符需要表达式参数列表
- 存储模板类型以强制转换回派生<T>
- 类型总是使用其大小存储在内存中吗
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 将载体和cv :: mat to Disk的存储结构 - C 中的数据序列化
- 如何在打开的 cv 中使用向量将一些浮点值存储在 for 循环中
- 将CV :: MAT实例存储在C 中的堆上
- 将 cv::Mat 存储在字节数组中,以便将数据传输到服务器
- 打开CV存储文件错误:
- c++ OpenCV最大存储容量cv::Mat
- 是否可以存储cv::指向cv::Mat ?
- 声明一个结构并立即用cv限定符或存储持续时间说明符对其进行实例化
- 存储其他信息以及 cv::Mat 元素