rows是高 cols是宽
#include <opencv2/opencv.hpp>
#include <iostream>
int main(){
// 新建4x5大小的0 矩阵 不要用4行5列来理解
cv::Mat zeros = cv::Mat::zeros(cv::Size(4,5),CV_8UC1);
std::cout<<zeros<<std::endl;
std::cout<<zeros.rows<<std::endl;
std::cout<<zeros.cols<<std::endl;
}
输出:
[ 0, 0, 0, 0;
0, 0, 0, 0;
0, 0, 0, 0;
0, 0, 0, 0;
0, 0, 0, 0]
5
4
利用fillPoly对矩形区域填充值
实际业务中一般都是填充不规则区域,这里为了演示的直观点,直接填充了一个矩形区域,我们将4x5大小的矩阵 第1,2(起点为0)行全部填充1
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
int main(){
// 新建4x5大小的0 矩阵 不要用4行5列来理解
cv::Mat zeros = cv::Mat::zeros(cv::Size(4,5),CV_8UC1);
// std::cout<<zeros<<std::endl;
// std::cout<<zeros.rows<<std::endl;
// std::cout<<zeros.cols<<std::endl;
std::vector<cv::Point> pts;
pts.push_back(cv::Point(0,1));
pts.push_back(cv::Point(0,2));
pts.push_back(cv::Point(3,1));
pts.push_back(cv::Point(3,2));
std::vector<std::vector<cv::Point>> ppts;
ppts.push_back(pts);
cv::fillPoly(zeros , ppts, (1));
std::cout<<zeros<<std::endl;
}
输出:
[ 0, 0, 0, 0;
1, 1, 1, 1;
1, 1, 1, 1;
0, 0, 0, 0;
0, 0, 0, 0]
.at 取值不是x,y应该是y,x
假设我现在需要把上面第1,2(起点为0)填充为1的矩阵,取出点(1,0)的坐标
- 是用cv::Point的点来取
- 或者是用y,x的顺序来取
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
int main(){
// 新建4x5大小的0 矩阵 不要用4行5列来理解
cv::Mat zeros = cv::Mat::zeros(cv::Size(4,5),CV_8UC1);
// std::cout<<zeros<<std::endl;
// std::cout<<zeros.rows<<std::endl;
// std::cout<<zeros.cols<<std::endl;
std::vector<cv::Point> pts;
pts.push_back(cv::Point(0,1));
pts.push_back(cv::Point(0,2));
pts.push_back(cv::Point(3,1));
pts.push_back(cv::Point(3,2));
std::vector<std::vector<cv::Point>> ppts;
ppts.push_back(pts);
cv::fillPoly(zeros , ppts, (1));
std::cout<<zeros<<std::endl;
// std::cout<<(int)zeros.at<unsigned char>(1,0)<<std::endl; // 错误的
std::cout<<(int)zeros.at<unsigned char> (cv::Point(1,0))<<std::endl;
std::cout<<(int)zeros.at<unsigned char>(0,1)<<std::endl;
}
输出:
[ 0, 0, 0, 0;
1, 1, 1, 1;
1, 1, 1, 1;
0, 0, 0, 0;
0, 0, 0, 0]
0
0
cv::range 注意区间是左闭右开
现在我们打印上面矩阵的所有行,0-2列(起点为0),下面的代码实际没有打印出第二列
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
int main(){
// 新建4x5大小的0 矩阵 不要用4行5列来理解
cv::Mat zeros = cv::Mat::zeros(cv::Size(4,5),CV_8UC1);
// std::cout<<zeros<<std::endl;
// std::cout<<zeros.rows<<std::endl;
// std::cout<<zeros.cols<<std::endl;
std::vector<cv::Point> pts;
pts.push_back(cv::Point(0,1));
pts.push_back(cv::Point(0,2));
pts.push_back(cv::Point(3,1));
pts.push_back(cv::Point(3,2));
std::vector<std::vector<cv::Point>> ppts;
ppts.push_back(pts);
cv::fillPoly(zeros , ppts, (1));
std::cout<<zeros<<std::endl;
// std::cout<<(int)zeros.at<unsigned char>(1,0)<<std::endl; // 错误的
// std::cout<<(int)zeros.at<unsigned char> (cv::Point(1,0))<<std::endl;
// std::cout<<(int)zeros.at<unsigned char>(0,1)<<std::endl;
std::cout<<zeros(cv::Range::all(),cv::Range(0,2))<<std::endl; //右边是开区间
}
输出:
[ 0, 0, 0, 0;
1, 1, 1, 1;
1, 1, 1, 1;
0, 0, 0, 0;
0, 0, 0, 0]
[ 0, 0;
1, 1;
1, 1;
0, 0;
0, 0]