Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

My version of the function:

void copy_matrix(const Mat &src, Mat &dst, const Mat &indices) {
    for (int i=0; i<indices.rows; i++) {
        dst.push_back(src.row(indices.at<int>(i)));
    }
}

Code sample:

    Mat indices(3,1,CV_32SC1); // n*1 matrix storing the row index, up to index 165600
    indices.at<int>(0,0) = 3;
    indices.at<int>(1,0) = 4;
    indices.at<int>(2,0) = 9;


    Mat dst;
    Mat src(100,2,CV_32SC1); // n*2 matrix
    for (int i = 0; i < src.rows; i++)
    {
        src.at<int>(i,0) = i;
        src.at<int>(i,1) = i+1;
    }
    copy_matrix(src, dst, indices);

As Daniil said, you should use 0-based numeration. Also if your matrix has only one row or only one column you can use only one index in "at" operator (see my variant of function). Also I can't understand why do you use "unsigned int" type for "at" operator. OpenCV doesn't support this type. In my opinion it is impossible to create a matrix with this type, because we don't have CV_32U depth variant. If you don't know type of your matrix "indices" you should use depth() or type() methods to detect it.

My version of the function:

void copy_matrix(const Mat &src, Mat &dst, const Mat &indices) {
    for (int i=0; i<indices.rows; i++) {
        dst.push_back(src.row(indices.at<int>(i)));
    }
}

Code sample:

    Mat indices(3,1,CV_32SC1); // n*1 matrix storing the row index, up to index 165600
    indices.at<int>(0,0) = 3;
    indices.at<int>(1,0) = 4;
    indices.at<int>(2,0) = 9;


    Mat dst;
    Mat src(100,2,CV_32SC1); // n*2 matrix
    for (int i = 0; i < src.rows; i++)
    {
        src.at<int>(i,0) = i;
        src.at<int>(i,1) = i+1;
    }
    copy_matrix(src, dst, indices);

As Daniil said, you should use 0-based numeration. Also if your matrix has only one row or only one column you can use only one index in "at" operator (see my variant of function). Also I can't understand why do you use "unsigned int" type for "at" operator. OpenCV doesn't support this type. In my opinion it is impossible to create a matrix with this type, because we don't have CV_32U depth variant. If you don't know type of your matrix "indices" you should use depth() or type() methods to detect it.