10

in OpenCV 2 and later there is method Mat::resize that let's you add any number of rows with the default value to your matrix is there any equivalent method for the column. and if not what is the most efficient way to do this. Thanks

AMCoded
  • 1,374
  • 2
  • 24
  • 39
  • I had a look to the online doc and it seems you don't have a function for adding columns. http://opencv.willowgarage.com/documentation/cpp/core_basic_structures.html?highlight=mat#Mat::resize – Jav_Rock Jan 13 '12 at 08:27

3 Answers3

30

Use cv::hconcat:

Mat mat;
Mat cols;

cv::hconcat(mat, cols, mat);
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Boris
  • 316
  • 2
  • 3
  • 6
    And don't try to find docs for this function. It is undocumented. – Vladimir Obrizan Oct 13 '14 at 13:37
  • 1
    Header code is here: https://github.com/Itseez/opencv/blob/master/modules/core/include/opencv2/core.hpp#L968 . For completeness, vertical concatination can be done with `vconcat()` and also `cv::Mat::push_back()` – Adi Shavit Jan 29 '15 at 10:43
  • Documentation: http://docs.opencv.org/trunk/d2/de8/group__core__array.html – I L Sep 14 '16 at 21:30
3

Worst case scenario: rotate the image by 90 degrees and use Mat::resize(), making columns become rows.

Community
  • 1
  • 1
karlphillip
  • 92,053
  • 36
  • 243
  • 426
  • Ok but that is worst case, what if my Mat contains CV_64FC1 and the size is too big (500*500) and i have to this for a big number of matrices, so I don't want to include the process of rotating or transposing twice such big matrices in the algorithm. – AMCoded Jan 13 '12 at 07:27
  • 5
    As I said, **worst case**. If I knew the best case I would have shared it with you. – karlphillip Jan 13 '12 at 11:19
2

Since OpenCV, stores elements of matrix rows sequentially one after another there is no direct method to increase column size but I bring up myself two solutions for the above matter, First using the following method (the order of copying elements is less than other methods), also you could use a similar method if you want to insert some rows or columns not specifically at the end of matrices.

void resizeCol(Mat& m, size_t sz, const Scalar& s)
{
    Mat tm(m.rows, m.cols + sz, m.type());
    tm.setTo(s);
    m.copyTo(tm(Rect(Point(0, 0), m.size())));
    m = tm;
}

And the other one if you are insisting not to include even copying data order into your algorithms then it is better to create your matrix with the big number of rows and columns and start the algorithm with the smaller submatrix then increase your matrix size by Mat::adjustROI method.

AMCoded
  • 1,374
  • 2
  • 24
  • 39