如何获得具有特定值的Mat的索引?

时间:2017-11-10 12:58:04

标签: c++ opencv

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

setUpClass

但是我有这个错误: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。同样在这个documentation状态:输出数组(在我的代码中为find()),其大小和类型与输入数组相同。 PLZ帮我修复了这段代码。

1 个答案:

答案 0 :(得分:1)

我仍然没有得到这个测试的重点,我想这将是其他算法...所以,我给你两个可能的解决方案。

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)。 可以在线测试此示例here

2)使用OpenCV

这里没有橄榄油测试。但这个也很容易做到。如果索引中有Mat,则只需要更改要模板化的迭代器。像这样:

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;

  }
}
相关问题