OpenCV Add columns to a matrix

23,436

Solution 1

Use cv::hconcat:

Mat mat;
Mat cols;

cv::hconcat(mat, cols, mat);

Solution 2

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

Solution 3

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.

Share:
23,436
AMCoded
Author by

AMCoded

Updated on August 17, 2020

Comments

  • AMCoded
    AMCoded over 3 years

    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
    AMCoded over 12 years
    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.
  • karlphillip
    karlphillip over 12 years
    As I said, worst case. If I knew the best case I would have shared it with you.
  • Vladimir Obrizan
    Vladimir Obrizan over 9 years
    And don't try to find docs for this function. It is undocumented.
  • Adi Shavit
    Adi Shavit over 9 years
    Header code is here: github.com/Itseez/opencv/blob/master/modules/core/include/… . For completeness, vertical concatination can be done with vconcat() and also cv::Mat::push_back()
  • I L
    I L over 7 years