OpenCV从Mat中提取某些行或列

本文介绍了如何使用OpenCV的Mat::rowRange和Mat::colRange方法高效地获取矩阵中特定行或列的指针。这两个操作为O(1)复杂度,为了不改变原矩阵,建议通过clone()函数复制数据创建新矩阵。示例展示了从一个3x3矩阵中提取行和列的结果。

Mat的rowRange和colRange可以获取某些范围内行或列的指针:

Mat::rowRange

Creates a matrix header for the specified row span.

C++:  Mat  Mat:: rowRange (int  startrow, int  endrow )  const
C++:  Mat  Mat:: rowRange (const Range&  r )  const
Parameters:
  • startrow – An inclusive 0-based start index of the row span.
  • endrow – An exclusive 0-based ending index of the row span.
  • r – Range structure containing both the start and the end indices.

The method makes a new header for the specified row span of the matrix. Similarly to Mat::row() and Mat::col() , this is an O(1) operation.

Mat::colRange

Creates a matrix header for the specified column span.

C++:  Mat  Mat:: colRange (int  startcol, int  endcol )  const
C++:  Mat  Mat:: colRange (const Range&  r )  const
Parameters:
  • startcol – An inclusive 0-based start index of the column span.
  • endcol – An exclusive 0-based ending index of the column span.
  • r – Range structure containing both the start and the end indices.

The method makes a new header for the specified column span of the matrix. Similarly to Mat::row() and Mat::col() , this is an O(1) operation.


由于这两个函数返回的是指向原矩阵内部位置的指针,所以最好再利用clone()函数进行数据拷贝创建新的矩阵,代码如下:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(){
	 Mat C = (Mat_<double>(3,3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
	 cout << "Total matrix:" << endl;
	 cout << C << endl;

	 Mat row = C.rowRange(1,3).clone();
	 cout << "Row range:" << endl;
	 cout << row << endl;
	
	 Mat col = C.colRange(1,3).clone();
	 cout << "Col range:" << endl;
	 cout << col << endl;
}


结果如下:

Total matrix
[0, -1, 0;
  -1, 5, -1;
  0, -1, 0]
Row range:
[-1, 5, -1;
  0, -1, 0]
Col range:
[-1, 0;
  5, -1;
  -1, 0]

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值