Iterators (迭代器)are specialized(专门) classes that are built to go over(遍历) each element of a collection(集合的每个元素), This application of the information-hiding principle makes scanning a collection easier and safer.
An iterator object for a cv::Mat instance(实例) can be obtained by first creating a cv::MatIterator_ object. As is the case with cv::Mat_, the underscore(下划线) indicates that this is a template subclass(模板子类). since(因为) image iterators are used to access the image elements, the return type(类型) must be known at the time of compilation(编译). The iterator is then declared as follows:
cv::MatIterator_<cv::Vec3b> it;
Alternatively(另外), you can also use the iterator type defined inside the Mat_ template class as follows:
cv::Mat_<cv::Vec3b>::iterator it;
Consequently(现在), our color reduction function is now written as follows:
//Scanning an image with iterators void colorReduce4(cv::Mat &image, int div = 64) { // obtain iterator at initial position cv::Mat_<cv::Vec3b>::iterator it = image.begin<cv::Vec3b>(); // obtain end position cv::Mat_<cv::Vec3b>::iterator itend = image.end<cv::Vec3b>(); // loop over(遍历)all pixels for (; it != itend; ++it) { (*it)[0] = (*it)[0] / div * div + div / 2; (*it)[1] = (*it)[1] / div * div + div / 2; (*it)[2] = (*it)[2] / div * div + div / 2; } } //Remember that the iterator here returns a cv::Vec3b instance because we are processing a color image.
用begin方法,在开始位置(本例中为图像的左上角)初始化迭代器。对于cv::Mat实例,可以使用image.begin<cv::Vec3b>()。还可以在迭代器上使用数学计算,例如若要从图像的第二行开始,可以用image.begin<cv::Vec3b>()+image.cols初始化cv::Mat迭代器。可以用运算符++来移动到下一个元素,也可以指定更大的步幅。例如用it+=10,对每10个像素处理一次。