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

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]可以很方便的访问。

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值