如何获得具有特定值的垫子的索引
How to get indices of a Mat with specific value?
我想找到一个等于特定值的数组的索引。所以我写了这个代码:
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;
}
}
- 如何获得QTreeWidgetItem中QComboBox索引更改的通知?
- 是否可以在C++中获得索引迭代器?
- 如果我将索引变量更改为零,并且合并函数中的k = 0,则获得合并排序的错误结果
- 获得给定向量的排列索引列表的最佳方法是什么?
- 为什么在将单词从文本文件C++到行进行多重映射时获得额外的索引值
- 如何获得具有多个索引的对象列表
- 如何使用索引获得特定值
- 如何获得具有特定值的垫子的索引
- 如何使用STL获得中值的索引
- 提升hana获得第一匹配的索引
- 如何获得选择点索引与QwtPlotPicker
- 如何获得指针在QTreeWidget索引
- 如何从c++列表中获得指定索引处的元素
- 我如何在QTableWidget中获得多个选定行的索引
- 如何在C中显示输出时获得链表索引
- 在c++中,当元组的元素索引在运行时已知时,是否有可能获得该元素的类型?
- 获得映射迭代器索引的最有效方法?c++
- 如何在字符数组的特定索引处获得实际值
- 如何在CMenu对象中获得所有子菜单的零基索引
- 如何在std::deque中获得元素的索引?