【问题标题】:Subtract a vector from each row of matrix in opencv?从opencv中的每一行矩阵中减去一个向量?
【发布时间】:2015-05-15 08:59:11
【问题描述】:

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

【问题讨论】:

    标签: c++ opencv


    【解决方案1】:

    如何逐行减去:

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

    【讨论】:

      【解决方案2】:

      没有你想要的内置函数,但是这些选项呢:

      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;
      

      【讨论】:

        猜你喜欢
        • 2021-08-13
        • 2014-08-22
        • 1970-01-01
        • 2011-07-17
        • 2014-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多