如何获得具有特定值的垫子的索引

How to get indices of a Mat with specific value?

本文关键字:索引 何获得      更新时间:2023-10-16

我想找到一个等于特定值的数组的索引。所以我写了这个代码:

vector<int> _classes = { 2,2,1,1,3,3,3,3,5,5,4,4,5,6,6 };
vector<int> labelVec = {1,2,3,4,5,6};
vector<int> index;
for (int i = 0; i < labelVec.size(); i++)
{
compare(_classes, labelVec[i], index, CMP_EQ);
std::vector<int>::iterator nn = find(index.begin(), index.end(), 255);
}

但我有一个错误:Unhandled exception at 0x760B5608 in compareFuncTest.exe: Microsoft C++ exception: cv::Exception at memory location 0x004DDC44.如果我把index定义为Mat,这个问题就会得到解决。但如果我将index定义为Mat,则不能使用fromfind()。在本文档中还说明:输出数组(在我的代码中为index),其大小和类型与输入数组相同。PLZ帮助我修复此代码。

我仍然不明白这个测试的意义,我想这将在其他算法中。。。所以,我给你两个可能的解决方案。

1) 无OpenCV

首先,你必须知道

std::vector<int>::iterator nn = find(index.begin(), index.end(), 255);

只会给你第一次机会。知道了这一点,这里有一种方法可以检查标签是否在_classes向量内。

#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> _classes = { 2,2,1,1,3,3,3,3,5,5,4,4,5,6,6 };
std::vector<int> labelVec = {1,2,3,4,5,6,7};
for (const auto& label: labelVec)
{    
std::vector<int>::iterator nn = find(_classes.begin(), _classes.end(), label);
if (nn != _classes.end())
{
std::cout << "I got the value from _classes: " << *nn << std::endl;
} else 
{
std::cout << "I couldn't find the value with label:" << label << std::endl;
}
}
}

在这里,我迭代所有标签(就像您所做的那样),然后在类中直接使用find,但使用label变量。然后我检查我是否找到了标签,如果没有,它会给你一个等于_classes.end()的值,如果你试图使用它,就会出现错误(看看没有找到的额外标签7)。这个例子可以在这里在线测试。

2) 带OpenCV

这里没有蹦床测试。但这个也很容易做到。如果你有一个Mat-in索引,你只需要更改要模板化的迭代器。像这样:

auto nn = find(index.begin<int>(), index.end<int>(), 255);

如果你有一个cv::Mat类,你也可以像以前的方法一样,跳过比较部分(这会更快)

更新

既然你想要的是索引和所有索引,那么你必须对其进行迭代:/如果你想要这些值,你可以使用copy_if。您可以创建一个lambda函数来轻松完成这项工作。

像这样:

#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
auto getIndices = [](const std::vector<int>& vec, const int value){
std::vector<int> result;
for (size_t t = 0; t < vec.size(); t++)
{
if (vec[t] == value)
{
result.push_back(static_cast<int>(t));
}
}
return result;
};
std::vector<int> _classes = { 2,2,1,1,3,3,3,3,5,5,4,4,5,6,6 };
std::vector<int> labelVec = {1,2,3,4,5,6,7};
for (const auto& label: labelVec)
{    
std::vector<int> nn = getIndices(_classes, label);
std::cout << "I got the following indices for value"<< label<< ": [ ";
for (const auto& n : nn)
{
std::cout << n << ",";
}
std::cout << " ]" << std::endl;
}
}