如何从mex函数返回矩阵结构
How to return a matrix structure from a mex function?
我有一个定义3d数组的结构,大小已知:
struct uchar3
{
unsigned char x, y, z;
};
我想通过mex函数返回它,以便在matlab中像三维数组一样使用它,就像图像一样。如何做到这一点?
编辑:
这是我使用的功能的一部分。
foo(uchar3 **imagePtr, Mat Im){
unsigned char *cvPtr = Im.ptr<unsigned char>(0);
for (size_t i = 0; i < Im.rows * Im.cols; ++i) {
(*imagePtr)[i].x = cvPtr[3 * i + 0];
(*imagePtr)[i].y = cvPtr[3 * i + 1];
(*imagePtr)[i].z = cvPtr[3 * i + 2];
}
}
谢的代码:
cv::Mat imageRGB;
cv::cvtColor(OutPutMat, imageRGB, CV_BGR2RGB);
// uc3 is populated here
mwSize sz[3];
sz[0] = imageRGB.rows; // matlab is row first
sz[1] = imageRGB.cols;
sz[2] = 3;
plhs[0] = mxCreateNumericArray( 3, sz, mxDOUBLE_CLASS, // create double array, you can change the type here
mxREAL ); // create real matrix
float *cvPtr = imageRGB.ptr<float>(0);
float* p = (float*)mxGetData(plhs[0]); // get a pointer to actual data
for ( size_t y = 0 ; y < imageRGB.rows ; y++ ) {
for ( size_t x = 0; x < imageRGB.cols ; x++ ) {
int i = y * imageRGB.cols + x; // opencv is col first
p[ x * imageRGB.rows + y ] = cvPtr[3 * i + 0];
p[ imageRGB.cols * imageRGB.rows + x * imageRGB.rows + y ] = cvPtr[3 * i + 1];
p[ 2*imageRGB.cols * imageRGB.rows + x * imageRGB.rows + y ] = cvPtr[3 * i + 2];
}
}
您需要使用mxCreateNumericArray
uchar3 uc3;
// uc3 is populated here
mwSize sz[3];
sz[0] = Im.rows; // matlab is row first
sz[1] = Im.cols;
sz[2] = 3;
mxArray* pOut = mxCreateNumericArray( 3, sz, mxDOUBLE_CLASS // create double array, you can change the type here
mxREAL ); // create real matrix
double* p = (double*)mxGetData(pOut); // get a pointer to actual data
for ( size_t y = 0 ; y < Im.rows ; y++ ) {
for ( size_t x = 0; x < Im.cols ; x++ ) {
int i = y * Im.cols + x; // opencv is col first
p[ x * Im.rows + y ] = cvPtr[3 * i + 0];
p[ Im.cols*Im.rows + x * Im.rows + y ] = cvPtr[3 * i + 1];
p[ 2*Im.cols*Im.rows + x * Im.rows + y ] = cvPtr[3 * i + 2];
}
}
// set one of your mexFunction's outputs to pOut
在mex函数中执行以下操作:
plhs[0] = valueStruct(Test,Test2);
其中ValueStruct是函数
mxArray* valueStruct(const double& d,const double& d2)
{
mxArray* p = mxCreateStructMatrix(1,1,2,_fieldnames);
if (!p)
mexErrMsgIdAndTxt("error","Allocation error");
mxSetField(p,0,"d",mxArray(d));
mxSetField(p,0,"d2",mxArray(d2));
return p;
}
有关更多信息,可以参考mxCreateStructMatrix文档。
对于mxSetField。
例如,您可以引用mexopencv,它使用mxArray类创建struct,您可以在这里找到它。
相关文章:
- 奇怪的结构&GCC&clang(void*返回类型)
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 将大括号括起来的初始值设定项列表作为结构返回
- 从返回的顶点缓冲区查询顶点结构
- 通过 NIF 从C++返回自定义数据结构
- 在类中返回结构时出现问题
- 为什么我们使用在C++中返回数据结构的函数?
- 为什么结构化绑定不使用"auto&"返回对结构成员的引用,而是返回成员本身
- 在 C 函数中返回结构会导致分段错误
- 如何实现返回受保护结构的私有函数
- 如何防止引用返回的私有结构的突变
- 在Cython中定义C 结构返回类型
- MEMCMP以相同(零值)位字段结构返回非零
- 错误:"运算符="不匹配 |结构返回类型
- C 结构返回真实,但是为什么
- C++使用结构返回多个值
- 操作员重新分配功能/结构返回什么
- 使用用户输入来从一个结构返回多个值
- 将结构返回为空
- C++ 从 vector 获取结构 &返回指向非初始化结构的指针