14

我想按此顺序将矩阵 A 的第 0、2 和 4 行复制到 B 中。让 A = [a0, a1, a2, a3, a4]^T ,其中 a_i 是行向量,那么 B 应该是:[a0, a2, a4]^T。

下面的代码可以满足我的要求,但我想知道是否有更漂亮的解决方案(可能使用 Eigen)?

#include <iostream>
#include <vector>
#include <opencv/cv.h>


int main(int argc, char **argv) {
    const int num_points = 5;
    const int vec_length = 3;
    cv::Mat A(num_points, vec_length, CV_32FC1);
    cv::RNG rng(0); // Fill A with random values
    rng.fill(A, cv::RNG::UNIFORM, 0, 1);
// HACK Ugly way to fill that matrix .
    cv::Mat B = cv::Mat(3,vec_length, CV_32FC1);
    cv::Mat tmp0 = B(cv::Rect(0,0,vec_length,1));
    cv::Mat tmp1 = B(cv::Rect(0,1,vec_length,1));
    cv::Mat tmp2 = B(cv::Rect(0,2,vec_length,1));
    A.row(0).copyTo(tmp0);
    A.row(2).copyTo(tmp1);
    A.row(4).copyTo(tmp2);

    std::cout << "A: " << A << std::endl;
    std::cout << "B: " << B << std::endl;
    return 0;
}
4

4 回答 4

25

OpenCV 2.4.1 中的方式是:

A.row(0).copyTo(B.row(0));
A.row(2).copyTo(B.row(1));
A.row(4).copyTo(B.row(2));
于 2012-08-08T16:36:49.190 回答
19

我发现push_back

创建Bsize 0 x vec_length然后使用push_back从添加选定的行A

#include <iostream>
#include <vector>
#include <opencv/cv.h>


int main(int argc, char **argv) {
    const int num_points = 5;
    const int vec_length = 3;
    cv::Mat A(num_points, vec_length, CV_32FC1);
    cv::RNG rng(0); // Fill A with random values
    rng.fill(A, cv::RNG::UNIFORM, 0, 1);
    cv::Mat B = cv::Mat(0,vec_length, CV_32FC1);
    B.push_back(A.row(0));
    B.push_back(A.row(2));
    B.push_back(A.row(4));
    std::cout << "A: " << A << std::endl;
    std::cout << "B: " << B << std::endl;
    return 0;
}
于 2011-08-25T11:09:09.407 回答
1

由于它们是不连续的,我认为没有任何捷径。在这种特殊情况下,您可以使用循环使代码更清晰:

for (int i=0; i<3; i++) {
    cv::Mat tmp = B(cv::Rect(0,i,vec_length,1));
    A.row(i * 2).copyTo(tmp);
}
于 2011-08-09T12:53:44.027 回答
0
Mat row = old.row(0);
old.row(0).copyTo(row);
new.push_back(row);
于 2014-03-10T18:58:04.110 回答