Mat自带了迭代器模板类,类名是MatIterator_,原型如下
template<typename _Tp> class MatIterator_ : public MatConstIterator_<_Tp> { public: typedef _Tp* pointer; typedef _Tp& reference; #ifndef OPENCV_NOSTL typedef std::random_access_iterator_tag iterator_category; #endif //! the default constructor MatIterator_(); //! constructor that sets the iterator to the beginning of the matrix MatIterator_(Mat_<_Tp>* _m); //! constructor that sets the iterator to the specified element of the matrix MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0); //! constructor that sets the iterator to the specified element of the matrix MatIterator_(Mat_<_Tp>* _m, Point _pt); //! constructor that sets the iterator to the specified element of the matrix MatIterator_(Mat_<_Tp>* _m, const int* _idx); //! copy constructor MatIterator_(const MatIterator_& it); //! copy operator MatIterator_& operator = (const MatIterator_<_Tp>& it ); //! returns the current matrix element _Tp& operator *() const; //! returns the i-th matrix element, relative to the current _Tp& operator [](ptrdiff_t i) const; //! shifts the iterator forward by the specified number of elements MatIterator_& operator += (ptrdiff_t ofs); //! shifts the iterator backward by the specified number of elements MatIterator_& operator -= (ptrdiff_t ofs); //! decrements the iterator MatIterator_& operator --(); //! decrements the iterator MatIterator_ operator --(int); //! increments the iterator MatIterator_& operator ++(); //! increments the iterator MatIterator_ operator ++(int); };
实例化迭代器对象如下:
Mat image ( 80, 60, CV_8UC3 ); MatIterator_<Vec3b>color = image.begin<Vec3b>(), color2 = image.end<Vec3b>();
上面演示实例化了2个对象,一个是color,另一个是color2;在初始化的时候显式的给2个对象赋了值;赋值形式比较奇怪(image.begin<Vec3b>()),在bigin函数后面加入了类型说明,因为bgein()函数返回的是MatIterator_模板对象,所以在实例化的时候要加上<Vec3b>。
begin函数声明如下(在Mat类中)
template<typename _Tp> MatIterator_<_Tp> begin(); template<typename _Tp> MatConstIterator_<_Tp> begin() const;
begin函数定义如下:[由于begin函数是在Mat类中声明,所以定义的时候要加上Mat::域说明符]
template<typename _Tp> inline MatIterator_<_Tp> Mat::begin() { CV_DbgAssert( elemSize() == sizeof(_Tp) ); return MatIterator_<_Tp>((Mat_<_Tp>*)this); }
begin函数return语句是先讲当前对象转化为Mat模板类对象,然后再调用Mat迭代器模板的构造函数初始化一个迭代器对象,再返回给调用者,所以用这个函数初始化迭代器对象时,会有image.begin<Vec3b>()这么奇怪的写法。