我有一个 cv::Mat
必须符合以下尺寸480 x 640 x 32
.
你能告诉我如何访问这个结构中的数据吗?假设我想从位置 [2, 2, 2]
访问元素.我该怎么做?
编辑 1:
我试过使用这个 template<typename T> const T& Mat::at(int i, int j, int k) const
但我收到以下运行时错误:
编辑 2:
下面是我使用代码的方式:
cv::Mat f(382,510,32);
f=Utils::toMat(features);
cout<<f.at<double>(1,1,1);
哪里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);
首先,您弄错了cv::Mat
的构造函数http://docs.opencv.org/modules/core/doc/basic_structures.html#mat-mat : 你的值 32 被用作类型,导致一些未定义的行为。
你必须使用这个
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.
然后,你的 Utils::toMat
函数看起来调试起来真的很复杂......我建议你阅读更多关于文档的内容,并且可能你重新实现初始化(填充) 你的矩阵使用 at
方法:
f.at<double>(x,y,z) = ...
关于c++ - 如何从 cv::Mat 访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17305231/