cv::Mat初始化、赋值初始化与访问方式

初始化

常量赋值初始化

cpp 复制代码
cv::Mat m = (cv::Mat_<float>(3,1) << 1, 2, 1.0);

指定类型和大小的二维数组

cpp 复制代码
cv::Mat m(int rows, int cols, int type);
cv::Mat m(cv::Size sz, int type);

初始化值均为0

cpp 复制代码
//二维数组,类型CV_8UC3, 初始化值cv::Scalar(100, 1, 1)
cv::Mat mat = cv::Mat::zeros(int rows, int cols, CV_8UC3, cv::Scalar(100, 1, 1)); 
cv::Mat mat = cv::Mat::ones(rows, cols, CV_32F); // 全1
cv::Mat mat = cv::Mat::eye(rows, cols, CV_64F); // 单位矩阵

数组赋值

cpp 复制代码
char* data = new char[15];
cv::Mat m3(3, 5, CV_8UC1, data);
//或者, 数据位数对齐
cv::Mat m4(1, 5, CV_8UC3, data);
cv::Mat m6(cv::Size(3, 5), CV_8UC1, data);

指定类型多维数组

cpp 复制代码
 7、指定类型的多维数组
    cv::Mat m(int ndims, const int* sizes, int type);
    int size[3] = { 3, 2, 2 };
    cv::Mat m7(3, size, CV_8UC1);
    //多维赋值
 		int matSize2[] = { 2,2,2 };//每一维元素的个数:8:行,10:列
    char* data2 = new char[8];
    cv::Mat m9(3, matSize2, CV_8UC1, data2);
cpp 复制代码
//使用cv::Vec定义相同类型、大小为n的一维数组初始化
cv::Vec<float, 10> data1{ 1,2,3,4,5, 6,7,8,9,10 };
cv::Mat m1(data1, true);
//使用cv::Matx定义相同类型、大小为mxn的二维数组
cv::Matx<float, 2, 4> data2{ 1,2,3,4,5,6,7,7 };
cv::Mat m2(data2, true);
//使用STL vector定义相同类型的一维数组
std::vector<float> vec{1, 2, 3, 4, 5, 6};
cv::Mat m3(vec, true);

访问:

1、 at 访问

If matrix is of type CV_8U then use Mat.at<uchar >(y,x).

If matrix is of type CV_8S then use Mat.at<schar >(y,x).

If matrix is of type CV_16U then use Mat.at<ushort >(y,x).

If matrix is of type CV_16S then use Mat.at<short >(y,x).

If matrix is of type CV_32S then use Mat.at<int >(y,x).

If matrix is of type CV_32F then use Mat.at<float >(y,x).

If matrix is of type CV_64F then use Mat.at<double >(y,x).

If matrix is of type CV_8UC3 then use Mat.at<Vec3b>(y,x)[0]

优点:直观好理解

缺点:访问速度相对慢

2、ptr指针进行访问

cpp 复制代码
cvInitMatHeader(&mat,3,2,CV_32FC3,data);//3通道
int nChannels = 3;
for(int x=0;x<mat.rows;++x){
	float *p = (float *)(mat.data.ptr + x*mat.step);//指向每一行的起始位置
for(int y=0;y<mat.cols;++y){
		float value[3];
	 value[0] = *(p+y*nChannels);
	 value[1] = *(p+y*nChannels+1);
	 value[2] = *(p+y*nChannels+2);
	 }
 }
相关推荐
华农DrLai几秒前
什么是角色扮演Prompt?为什么给AI设定身份能提升表现?
人工智能·深度学习·ai·prompt·bert·transformer
大傻^2 分钟前
SpringAI2.0 向量存储生态:Redis、Amazon S3 与 Bedrock Knowledge Base 集成
数据库·人工智能·向量存储·springai
qq_526099132 分钟前
工业视觉时代,图像采集卡如何重构数据采集
图像处理·数码相机·计算机视觉·自动化
咋个办呢5 分钟前
AI智能体自学打卡:一份非常全的 Markdown Prompt 模板(可做减法)
人工智能·ai·prompt·智能体
彷徨的蜗牛11 分钟前
智能AI自动化协同发文系统架构设计:从理论到实践的完整指南
人工智能·系统架构·自动化
许国栋_12 分钟前
B2B企业如何建设价值管理办公室(VMO)?实践与落地解析
人工智能·安全·云计算·产品经理
一RTOS一15 分钟前
从PLC到机器人:实时操作系统如何决定能力上限
人工智能·机器人·鸿道操作系统·鸿道实时操作系统·国产嵌入式操作系统选型·鸿道机器人操作系统
大傻^20 分钟前
Spring AI 2.0 企业级 RAG 架构:混合检索、重排序与多模态知识库
人工智能·spring·架构·多模态·rag·混合检索·重排序
yiyu071622 分钟前
3分钟搞懂深度学习AI:实操篇:Attention
人工智能·深度学习
s090713626 分钟前
保姆级教程十二:USB摄像头接入!ZYNQ+OpenCV+FPGA硬件加速图像处理实战(视觉终极篇)
图像处理·opencv·fpga开发·zynq·硬件加速