简体   繁体   English

如何从cv :: Mat访问数据

[英]How to access data from cv::Mat

I have a cv::Mat which hase to following size 480 x 640 x 32 . 我有一个cv::Mat具有以下尺寸480 x 640 x 32

Can you please show me how can I access the data within this structure? 您能告诉我如何在此结构中访问数据吗? Let's say that I want to access the element from position [2, 2, 2] . 假设我要从位置[2, 2, 2]访问该元素。 How can I do this? 我怎样才能做到这一点?

EDIT 1: 编辑1:

I have tried using this template<typename T> const T& Mat::at(int i, int j, int k) const but I receive the following runtime error : 我尝试使用此template<typename T> const T& Mat::at(int i, int j, int k) const但是我收到以下运行时错误:

在此处输入图片说明

EDIT 2: 编辑2:

Here is how I am using the code : 这是我使用代码的方式:

cv::Mat f(382,510,32); 
f=Utils::toMat(features); 
cout<<f.at<double>(1,1,1); 

where toMat is detailed bellow. 下面是toMat的详细信息。

cv::Mat Utils::toMat( mxArray* p_)
{
mwSize ndims_= mxGetNumberOfDimensions(p_);
const mwSize* dims=mxGetDimensions(p_);
std::vector<int> d(dims, dims+ndims_);
int ndims = (d.size()>2) ? d.size()-1 : d.size();
int nchannels = (d.size()>2) ? *(d.end()-1) : 1;
int depth=CV_64F;
std::swap(d[0], d[1]);
cv::Mat mat(ndims, &d[0], CV_MAKETYPE(depth, nchannels));
// Copy each channel.
std::vector<cv::Mat> channels(nchannels);
std::vector<mwSize> si(d.size(), 0); // subscript index
int type = CV_MAKETYPE(depth, 1); // Source type
for (int i = 0; i<nchannels; ++i)
{
    si[d.size()-1] = i;
    void *pd = reinterpret_cast<void*>(
            reinterpret_cast<size_t>(mxGetData(p_))+
            mxGetElementSize(p_)*mxCalcSingleSubscript(p_, si.size(), &si[0]));
    cv::Mat m(ndims, &d[0], type, pd);
    // Read from mxArray through m
    m.convertTo(channels[i], CV_MAKETYPE(depth, 1));
}
cv::merge(channels, mat);
return  mat;
}
> cv::Mat f(382,510,32);

To start with, you got wrong the constructor of cv::Mat http://docs.opencv.org/modules/core/doc/basic_structures.html#mat-mat : your value 32 is used as type, leading to some undefined behaviour. 首先,您弄错了cv::Mat http://docs.opencv.org/modules/core/doc/basic_structures.html#mat-mat的构造函数:您的值32被用作类型,导致一些未定义行为。

You have to use this 你必须用这个

 Mat::Mat(int ndims, const int* sizes, int type)

 const int[] mySizes = {382,510,32}; //I hope I have written this correctly...
 cv::Mat f(3,mySizes,CV_64F). // You find CV_64 in the same documentation page.

Then, your Utils::toMat functions looks really complicated to debug... I suggest that you read a little bit more about the documentation, and possibly that you re-implement the initialization (filling) of your matrix using the at method: 然后,您的Utils::toMat函数看起来调试起来真的很复杂...我建议您阅读一些有关文档的信息,并可能使用at方法重新实现矩阵的初始化(填充):

 f.at<double>(x,y,z) = ...

You can use .at<element_type>(i,j,k); 您可以使用.at<element_type>(i,j,k);

with reference : 参考

template<typename T> const T& Mat::at(int i, int j, int k) const

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM