OpenCV——Mat遍历的三种方法

Mat的存储方式  

三通道3*3矩阵存储方式

在这里插入图片描述

image.at<uchar>(i,j):取出灰度图像中i行j列的点。

image.at<Vec3b>(i,j)[k]:取出彩色图像中i行j列第k通道的颜色点,k=[0,1,2],分别代表B,G,R。

uchar,Vec3b都是图像像素值的类型,在core里它是通过typedef Vec<T,N>来定义的,N代表元素的个数,T代表类型。
 

先随便定义一个Mat

Mat mat(3, 4, CV_8UC3, Scalar(0, 0, 1));
cout << mat << endl;

1. 通过 .at<typename>(i,j) 遍历

 for (int i = 0; i < mat.rows; ++i) {
        for (int j = 0; j < mat.cols; ++j) {
            Vec3b vc = mat.at<Vec3b>(i, j);
            cout << (int)vc.val[0] << " " << (int)vc.val[1] << " " << (int)vc.val[2] << " ";
        }
        cout << endl;
    }

 2. 通过行指针 .ptr<uchar>(k)来遍历

for (int i = 0; i < mat.rows; i ++) {
        uchar *ptr = mat.ptr<uchar>(i);
        for (int j = 0; j < mat.cols*mat.channels(); ++j) {
            cout << (int)ptr[j] << " ";
        }
        cout << endl;
    }

3. 通过迭代器Mat_iterator来遍历

MatIterator_<Vec3b> it = mat.begin<Vec3b>();
    MatIterator_<Vec3b> end = mat.end<Vec3b>();
    for (int i = 0; it != end; ++it) {
        cout << (int)(*it).val[0] << " " << (int)(*it).val[1] << " " << (int)(*it).val[2];
        ++i;
        if (i % (mat.cols * mat.channels()) != 0) {
            cout << " ";
        }
        if ((i % mat.cols) == 0) {
            cout << endl;
        }
    }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值