【问题标题】:How to return indices of a specific value from a matrix (Mat) in C++?如何从 C++ 中的矩阵 (Mat) 返回特定值的索引?
【发布时间】:2013-10-22 10:35:36
【问题描述】:

如何返回二维数组中特定值的索引?

这是我到目前为止所做的:

Mat *SubResult;

for(int i=0; i < height; i++){
    for(int j=0; j< width; j++){
       if(SubResult[i][j]<0){
          return [i][j];
       }
    }
}

这是我在您解释后所做的,但仍然出现错误:

void Filter(float* currentframe, float* previousframe, float* SubResult){

int width ;
int height ; 
std::vector< std::pair< std::vector<int>, std::vector<int> > > Index;
cv::Mat curr = Mat(height, width, CV_32FC1, currentframe);
cv::Mat prev = Mat(height, width, CV_32FC1, previousframe);
//cv::Mat Sub = Mat(height, width, CV_32FC1, SubResult);
cvSub(currentframe, previousframe, SubResult);
cv::Mat Sub = Mat(height, width, CV_32FC1, SubResult);

for(int i=0; i < height; i++){
    for(int j=0; j< width; j++){
       if(Sub[i][j] < 0){
         Index.push_back(std::make_pair(i,j));
       }
     }

}

} }

【问题讨论】:

    标签: c++ opencv matrix return return-value


    【解决方案1】:

    使用pair&lt;int,int&gt; 作为您的返回类型,并返回这样的一对:

    return make_pair(i, j);
    

    在接收端,调用者需要访问该对的元素,如下所示:

    pair<int,int> p = find_2d(.....); // <<== Call your function
    cout << "Found the value at (" << p.first << ", " << p.second << ")" << endl;
    

    【讨论】:

    • 我想告诉你我在你解释后做了什么,但stackoverflow不允许! :(
    • @user2758510 你为什么把Index 做成向量对的向量?看起来vector&lt;pairs&lt;int,int&gt; &gt; 应该也可以正常工作。
    【解决方案2】:

    您可以将其作为结构返回:

    struct Index
    {
       std::size_t i, j;
    };
    
    return Index{i, j};
    

    另一种方式是std::pair:

    return std::make_pair(i, j);
    

    【讨论】:

      【解决方案3】:

      为确保您的函数可以与Mat 的现有有效实例一起使用,请通过引用传递(因为它不会更改矩阵,所以将其设为const)。然后你可以返回一个std::pair 或者只是简单地填写通过引用传递的参数并返回bool 表示成功:

      bool foo(const Mat& img, int& x, int& y) {
          for(int i = 0; i < img.rows; i++) {
              for(int j = 0; j < img.cols; j++) {
                 if(img[i][j] < 0) {
                    x = j;
                    y = i;
                    return true;
                 }
              }
          }
          return false;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-04-19
        • 1970-01-01
        • 2016-09-16
        • 2016-10-31
        • 1970-01-01
        • 2013-07-05
        • 2018-08-29
        • 1970-01-01
        • 2019-04-15
        相关资源
        最近更新 更多