从opencv中的每一行矩阵中减去一个向量?

时间:2015-03-13 00:21:08

标签: c++ opencv

我有一个矩阵或Mat对象(比如M),一个行向量,也是一个Mat对象(比如说V)。我想从M的每一行中减去V.除了自己编写自定义代码之外,我在openCV中找不到任何一种方法。有什么帮助吗?

2 个答案:

答案 0 :(得分:4)

逐行减去怎么样:

for (int r = 0; r < M.rows; ++r) {
    M.row(r) = M.row(r) - V;
}

答案 1 :(得分:0)

没有内置功能可以满足您的需求,但这些选项如何:

cv::Mat1f M = cv::Mat1f::eye( 3, 3 );
cv::Mat1f V = ( cv::Mat1f( 3, 1 ) << 1.f, 2.f, 3.f );

// 1. Using a for-loop.
//
// More code but uses less memory.
const cv::Size size = M.size();
cv::Mat1f result1 = cv::Mat1f::zeros( 3, 3 );

for ( int y = 0; y < size.height; ++y )
{
    cv::Rect rect( 0, y, size.width, 1 );
    result1( rect ) = M( rect ) - V.t();
}

// 2. Avoiding a for-loop like in Matlab
//
// Less code but uses more memory.
cv::Mat1f ones = cv::Mat1f::ones( 3, 1 );
cv::Mat1f result2 = M - ones * V.t();

std::cout << "M = " << std::endl << M << std::endl;
std::cout << "V = " << V.t() << std::endl;
std::cout << "result1 = " << std::endl << result2 << std::endl;
std::cout << "result2 = " << std::endl << result2 << std::endl;