如何从C++中的矩阵 (Mat) 返回特定值的索引

How to return indices of a specific value from a matrix (Mat) in C++?

本文关键字:返回 索引 Mat C++      更新时间:2023-10-16

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

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

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 过滤器(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));
       }
     }
}

}}

使用 pair<int,int> 作为返回类型,并返回如下所示的一对:

return make_pair(i, j);

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

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

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

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

另一种方法是std::pair

return std::make_pair(i, j);

为了确保您的函数可以使用现有且有效的 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;
}