Home » C++ » How to obtain the Mat matrix elements

How to obtain the Mat matrix elements


front openCV from the official document of http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat

problem: for all positive sums in a matrix, you need to iterate over each element and add.

Idea one:

traversal, cumulative

double sum = 0; 

For (int i = 0; I < M.rows; i++) {

Const, double*, Mi = M.ptr (I);

For (int = J = 0; j< M.cols; j++) {

Sum = std:: Max (Mi[j], 0);


Idea two:

the idea of a violent, did not work very well. In sum before we can first determine the matrix is not continuous. If it is continuous, then you can put the whole matrix as a long one-dimensional array.

double sum = 0; 

Int cols = M.cols;

Int rows = M.rows;

If (M.isContinuous ()) {

Cols, =, cols, , rows;

Rows = 1;

For (int i = 0; I < rows; i++) {

Const, double, *Mi = M.ptr (I);

For (int = J = 0; j< cols; j++) {

Sum = std:: Max (Mi[j], 0);


The method of

is to determine in advance whether the M matrix is continuous. If continuous, then the outer for loop in the summation process only needs one time, which greatly reduces the overhead.


isContinuous () function explains:

This function returns the last detected matrix of each line is not continuous. In general, the 1*N matrix is continuous, (create) matrix function created is continuous. But if it is in the matrix extraction part of elements as a new matrix, such as col (), diag (function). There is the allocated data memory space for header information may not be continuous
This function is not continuous detection matrix and not by the ergodic matrix, but the detection head sign information matrix, this flag is the time to create the information in your head is calculated from the matrix, so the judgment matrix is continuous is a very fast operation.

Idea three:

STL template iterator can intelligently avoid the ends of each row that are not contiguous.

double sum = 0; 

MatConstIterator_, it = M.begin (), it_end = M.end ();

For (= it = = it_end; ++it) {

Sum = std:: Max (*it, 0);


The iterator of the

Mat matrix can be applied to any STL algorithm, including the sorting algorithm std:: sort ()