how to use opencv Mat reserve? with push_back

2.2k Views Asked by At

I want to use the opencv cv::Mat function push_back to add new rows to a matrix, but I want to precache the size of the matrix so that the data doesn't need to be constantly reallocated. The cv::mat::reserve function has a number of rows parameter, but that implies that you have to specify the number of columns (and data size first). So the code below I assume would give me one empty row at the beginning which I don't want. Is there a proper way to do this using reserve and push_back??

cv::Mat M(1, size_cols, CV_32FC1);
M.reserve(size_rows);
for (int i = 0; i < size_rows; i++)
{
  GetInputMatrix(A);
  M.push_back(A.row(i));
}

Note: though the example code doesn't show it I'm not sure of the exact size of the final matrix, but I can get a max value size to reserve.

2

There are 2 best solutions below

1
On

Using an empty mat in the beginning will be just fine. The column number and type will be determined via the first push_back.

cv::Mat M;  // empty mat in the beginning
M.reserve(size_rows);
for (int i = 0; i < size_rows; i++) {
    GetInputMatrix(A);
    M.push_back(A.row(i));
}
0
On

Well, according to documentation,

reserve does:

The method reserves space for sz rows. If the matrix already has enough space to store sz rows, nothing happens. If the matrix is reallocated, the first Mat::rows rows are preserved. The method emulates the corresponding method of the STL vector class.

That being said, as long as you don't that huge amount of data to store, nothing will happen.