课本解释两者为:
rowRange为指定的行span创建一个新的矩阵头,可取指定行区间元素
colRange为指定的列span创建一个新的矩阵头,可取指定列区间元素
自我初步理解:
rowRange(int x, int y) (其中y应小于等于行数,例如一个矩阵最大为5行,那么y最大为4) 的创建矩阵范围为从x行为首行开始,往后数y-x行。
例如:rowRange(0,3) 位 从第0行开始,往后数3行。即 0 、1、2行。
colRange(int x,int y)同理。
Mat.rowRange(int x,int y)和Mat.rowRange(range(int x,int y)得到的结果一样,函数取的实际行数y-x,只取到范围的左边界,而不取右边界。
(特别注意:网上好多的文章虽然测试结果正确,但是结论却是错误的,曾被误导的飘过~)
#include<stdio.h>
#include<opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
int main()
{
//初始化一个3*3的矩阵
Mat examples = (Mat_<float>(3, 3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
//取example中中特定范围的行列构成矩阵
Mat temp_row1 = examples.rowRange(Range(1, 2)); //取特定行
Mat temp_row2 = examples.rowRange(1, 2);
Mat temp_row3 = examples.rowRange(0, 2);
Mat temp_col = examples.colRange(1, 3); //取特定列
//n,p,m,q计数,用于控制矩阵元素的输出格式
int n = 0;
int p = 0;
int m = 0;
int q = 0;
int z = 0;
//输出初始矩阵的元素
cout << "examples:" << endl;
for (int i = 0; i<examples.rows; i++){
for (int j = 0; j<examples.cols; j++)
{
cout << examples.at<float>(i, j);
p++;
if (p % 3 == 0)cout << endl;
}
}
cout << endl;
//测试rowRange(Range(int x,int y))
cout << "temp_row1:" << endl;
for (int i = 0; i<temp_row1.rows; i++)
{
for (int j = 0; j<temp_row1.cols; j++){
cout << temp_row1.at<float>(i, j);
n++;
if (n % 3 == 0)
cout << endl;
}
}
cout << endl;
//测试rowRange(int x,int y)函数
cout << "temp_row2:" << endl;
for (int i = 0; i<temp_row2.rows; i++)
{
for (int j = 0; j<temp_row2.cols; j++){
cout << temp_row2.at<float>(i, j);
m++;
if (m % 3 == 0)
cout << endl;
}
}
cout << endl;
cout << "temp_row3:" << endl;
for (int i = 0; i < temp_row3.rows; i++)
{
for (int j = 0; j < temp_row3.cols; j++)
{
cout << temp_row3.at<float>(i, j);
z++;
if (z % 3 == 0)
cout << endl;
}
}
cout << endl;
//测试colRange(int x,int y)函数
cout << "temp_col:" << endl;
for (int i = 0; i<temp_col.rows; i++)
{
for (int j = 0; j<temp_col.cols; j++){
cout << temp_col.at<float>(i, j);
q++;
if (q % 2 == 0)
cout << endl;
}
}
return 0;
}
说明:部分代码来自网络