【opencv】图像数字化——认识OpenCV中的Mat类(4 访问单通道Mat对象中的值)

4 访问单通道Mat对象中的值

4.1使用成员函数at()

  • 格式:m.at(r,c),访问第r行c列
#include <opencv2/core/core.hpp>  
#include<iostream>  
using namespace std;
using namespace cv;
int main()
{
    //构造矩阵
    Mat m = (Mat_<int>(3, 2) << 1, 2, 3, 4, 5, 6);
    cout << m << endl;
    for (int r = 0; r < m.rows; r++) {
        for (int c = 0; c < m.cols; c++) {
            cout << m.at<int>(r, c) << ",";
        }
    }
    cout << endl;
    return 0;
}

在这里插入图片描述

4.2使用point类和成员函数at()

  • 格式:m.at(Point(c,r));
#include <opencv2/core/core.hpp>  
#include<iostream>  
using namespace std;
using namespace cv;
int main()
{
    //构造矩阵
    Mat m = (Mat_<int>(3, 2) << 1, 2, 3, 4, 5, 6);
    cout << m << endl;
    for (int r = 0; r < m.rows; r++) {
        for (int c = 0; c < m.cols; c++) {
            cout << m.at<int>(Point(c, r)) << ",";
        }
        cout << endl;
    }
    
    return 0;
}

在这里插入图片描述

4.3使用成员函数ptr()

  • 通过成员函数ptr获得指向每一行首地址的指针
#include <opencv2/core/core.hpp>  
#include<iostream>  
using namespace std;
using namespace cv;
int main()
{
    //构造矩阵
    Mat m = (Mat_<int>(3, 2) << 1, 2, 3, 4, 5, 6);
    cout << m << endl;
    for (int r = 0; r < m.rows; r++) {
        const int* ptr = m.ptr<int>(r);
        //打印第r行的所有值
        for (int c = 0; c < m.cols; c++) {
            cout << ptr[c] << ",";
        }
        cout << endl;
    }
    
    return 0;
}

在这里插入图片描述

4.4使用成员函数isContinuous()和ptr()

  • isContinuous()返回true代表行与行之间是连续存储的,那么所有的值都是连续存储的
#include <opencv2/core/core.hpp>  
#include<iostream>  
using namespace std;
using namespace cv;
int main()
{
    //构造矩阵
    Mat m = (Mat_<int>(3, 2) << 1, 2, 3, 4, 5, 6);
    cout << m << endl;
    if (m.isContinuous()) {
        //得到矩阵第一个值得地址
        int* ptr = m.ptr<int>(0);
        for(int n=0;n<m.rows*m.cols;n++){
            cout << ptr[n] << ",";
    }   
        cout << endl;
    }  
    return 0;
}

在这里插入图片描述

4.5使用成员变量step和data

  • step[0]代表每一行所占字节数
  • step[1]代表每一个数值所占字节数
  • data是指向第一个数值的指针
  • 访问int类型的单通道矩阵第r行第c列的值
  • 格式:((int)(m.data+m.step[0]r+cm.step[1]))
#include <opencv2/core/core.hpp>  
#include<iostream>  
using namespace std;
using namespace cv;
int main()
{
    //构造矩阵
    Mat m = (Mat_<int>(3, 2) << 1, 2, 3, 4, 5, 6);
    cout << m << endl;
    for (int r = 0; r < m.rows; r++) {
        for (int c = 0; c < m.cols; c++) {
            cout << *((int*)(m.data + m.step[0] * r + c * m.step[1])) << ",";
        }
    } 
        cout << endl;
    return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值