OPENCV学习笔记2-3_图像遍历(迭代器)

本文介绍如何使用迭代器遍历图像中的每个像素,并提供了一个颜色缩减功能的具体实现。通过使用cv::Mat迭代器,可以更安全高效地扫描图像集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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个像素处理一次。

转载于:https://www.cnblogs.com/yunfung/p/7553703.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值