OpenCV從Mat中提取某些行或列
阿新 • • 發佈:2019-01-28
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
- 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]