2012-01-10 18 views

回答

8

以下是NAryMatIterator文档的简短示例;它显示了如何创建,填充和在OpenCV中处理一个多维矩阵:

void computeNormalizedColorHist(const Mat& image, Mat& hist, int N, double minProb) 
{ 
    const int histSize[] = {N, N, N}; 

    // make sure that the histogram has a proper size and type 
    hist.create(3, histSize, CV_32F); 

    // and clear it 
    hist = Scalar(0); 

    // the loop below assumes that the image 
    // is a 8-bit 3-channel. check it. 
    CV_Assert(image.type() == CV_8UC3); 
    MatConstIterator_<Vec3b> it = image.begin<Vec3b>(), 
          it_end = image.end<Vec3b>(); 
    for(; it != it_end; ++it) 
    { 
     const Vec3b& pix = *it; 
     hist.at<float>(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f; 
    } 

    minProb *= image.rows*image.cols; 
    Mat plane; 
    NAryMatIterator it(&hist, &plane, 1); 
    double s = 0; 
    // iterate through the matrix. on each iteration 
    // it.planes[*] (of type Mat) will be set to the current plane. 
    for(int p = 0; p < it.nplanes; p++, ++it) 
    { 
     threshold(it.planes[0], it.planes[0], minProb, 0, THRESH_TOZERO); 
     s += sum(it.planes[0])[0]; 
    } 

    s = 1./s; 
    it = NAryMatIterator(&hist, &plane, 1); 
    for(int p = 0; p < it.nplanes; p++, ++it) 
     it.planes[0] *= s; 
} 

此外,检查出所述cv::compareHist功能的NAryMatIteratorhere另一使用示例。

+0

因此,一个3维数组应是这样的吗? int sz [] = {3,3,3}; Mat accumarray(3,sz,CV_8U,Scalar :: all(0)); accumarray.at (0,1,2)= 20; – garak 2012-01-11 00:42:39

+0

是的。这应该工作得很好。 – mevatron 2012-01-11 15:04:12

+0

好吧,上面的方法似乎不适用于4维矩阵。你知道原因吗? – garak 2012-01-16 14:52:28

1

要创建多维矩阵是大小100×100×,采用浮筒,一个信道,并与所有元素初始化为10你写这样的:

int size[3] = { 100, 100, 3 }; 
cv::Mat M(3, size, CV_32FC1, cv::Scalar(10)); 

要遍历和输出中的元素矩阵可以这样做:

for (int i = 0; i < 100; i++) 
    for (int j = 0; j < 100; j++) 
    for (int k = 0; k < 3; k++) 
     std::cout << M.at<cv::Vec3f>(i,j)[k] << ", "; 

然而,谨防使用多维矩阵的烦恼作为记录在这里:How do i get the size of a multi-dimensional cv::Mat? (Mat, or MatND)

+0

正是我在找的东西,简单又方便!谢谢。 – 2015-11-17 16:25:00