如何从C++中的矩阵 (Mat) 返回特定值的索引
How to return indices of a specific value from a matrix (Mat) in C++?
如何返回二维数组中特定值的索引?
这是我到目前为止所做的:
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;
}
相关文章:
- 在 C++ 中访问数组负索引处的内存不会返回垃圾
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 为什么 min_element() 返回最小元素的索引,而不是迭代器?
- 如何在C++中返回向量的从零开始的索引
- 返回向量的单个索引值
- C++函数返回两个 char 数组的相同索引元素
- 访问包含P的有效索引时返回空格的C++字符串
- 当我在网格/面中实现索引时,为什么它会返回OpenGl错误
- 为什么函数的任何索引处的下标运算符在C++中总是返回1
- 如何使用递归函数返回数组中整数的索引?
- "如何使用C++将字符串的第一个和最后一个索引返回到向量中?
- 当索引为 1 时,_BitScanReverse返回 0,这意味着根据 MS "no set bits were found"
- 从给定索引返回子字符字符串的函数
- 从字符串返回 i(索引)字
- 如何从函数返回索引?
- 如何使minmax_element在平局的情况下返回索引最少的元素
- QmetaObject :: IndexOfMethod返回到底返回索引
- boost ::几何查询返回索引
- 如何返回索引位置而不是值
- 遍历查找节点中的顶点并返回索引