OpenCV 2 学习笔记(20): 关于NAryMatIterator

来源:互联网 发布:按层次遍历二叉树c语言 编辑:程序博客网 时间:2024/05/21 09:16

NAryMatIterator 是一个n元多维数组迭代器,说到这他和MatIterator的区别,我想大家都已经了解了:

NAryMatIterator是一个Mat迭代器,而MatIterator是Mat元素的迭代器

而NAryMatIterator的作用就是可以用来同时访问具有相同类型和结构的Mat。有时候也可以使用MatIterator来循环操作每一个Mat,但是有时候这样做会比较麻烦。

让我们看一段代码,这段代码来自于:http://physics.nyu.edu/grierlab/manuals/opencv/classcv_1_1NAryMatIterator.html

 void normalizeColorHist(Mat& hist) { #if 1         // intialize iterator (the style is different from STL).     // after initialization the iterator will contain     // the number of slices or planes     // the iterator will go through     Mat* arrays[] = { &hist, 0 };     Mat planes[1];     NAryMatIterator it(arrays, planes);     double s = 0;     // iterate through the matrix. on each iteration     // it.planes[i] (of type Mat) will be set to the current plane of     // i-th n-dim matrix passed to the iterator constructor.     for(int p = 0; p < it.nplanes; p++, ++it)        s += sum(it.planes[0])[0];     it = NAryMatIterator(hist);     s = 1./s;     for(int p = 0; p < it.nplanes; p++, ++it)        it.planes[0] *= s; #elif 1     // this is a shorter implementation of the above     // using built-in operations on Mat     double s = sum(hist)[0];     hist.convertTo(hist, hist.type(), 1./s, 0); #else     // and this is even shorter one     // (assuming that the histogram elements are non-negative)     normalize(hist, hist, 1, 0, NORM_L1); #endif }

这段代码是规范化直方图的代码。首先声明一个指针数组arrays,至于最后一个元素怎么为0,我觉得应该和字符串中的'\0'的功能是一样的,因为在它的源代码中是以0判断结束的,所以这个0一定不可以少!

planes是将指针数组中的Mat放到这里面以便于一同访问。NAryMatIterator it(...)是它的初始化。这个要注意了,不管你的arrays里面的矩阵是几维的,planes存储的都是它的二维化的矩阵,也就是他先把矩阵根据列数将之二维化了,不要以为这个二维就是有很多行,很多列,它都统一转化为一行,元素个数个列,因为只有这样才可以使用image.cols和image.rows,因为二维以上的矩阵他们的返回值都是-1.

nplanes表示分组的个数,很明显这个程序中只有一组,it.planes[i]表示的是每一个数组,这样循环it就可以达到同时访问的目的。

其中的s+= sum(it.planes[0])[0]是指将第一个频道里的元素全部相加求和。这个例子里不涉及到多个矩阵,但是我们可以看到当有多个矩阵时利用it.planes[i]可以很方便的访问。

原创粉丝点击