c++ - 查找出现次数最多的值(cv::Vec3b)结果似乎是错误的

标签 c++ opencv

我试图通过 for 循环找到出现次数最多的值。我没有使用排序函数,因为 currentCharmostCharcv::Vec3b 值。程序如图:

for (int z = 0; z < temp.size(); z++)
{
    currentChar = temp[z];
    mostChar = temp[z];
    currentCount = 0;
    mostCount = 0;
    for (int i =0; i < temp.size(); i++)
    {
        cv::Vec3b c = temp[i];

        if (c == currentChar)
            currentCount++;

        if (currentCount > mostCount)
        {
            mostChar = currentChar;
            mostCount = currentCount;
        }
    }
}
std::cout << "most occurring values is" << mostChar << "with " << mostCount << " times!" << endl;

结果似乎很奇怪。我已经尝试了很多。不确定我的程序流程是否有问题。我习惯于做这样的事情,这很有效:

sort(temp.begin(), temp.end());
int currentChar = temp[0];
int mostChar = temp[0];
int currentCount = 0;
int mostCount = 0;
for (int i =0; i <temp.size(); i++)
{
    int c = temp[i];
    if (c == currentChar)
        currentCount++;
    else
    {
        if (currentCount > mostCount)
        {
            mostChar = currentChar;
            mostCount = currentCount;
        }
        currentChar = c;
        currentCount = 1;
    }
}

std::cout << "most occurring values is" << mostChar << "with " << mostCount << " times!" << endl;

现在没有排序功能并使用 for 循环,我的结果似乎很奇怪。任何想法?我试过:

if (c == currentChar)
    currentCount++;
else
{
    if ( currentCount > mostCount)
    {
            mostChar = currentChar;
        mostCount = currentCount;
    }
        currentChar = c;
        currentCount = 1;
    }
}

在for循环的方法中,不停地改,结果还是很奇怪。任何想法。自从我玩编程以来已经有一段时间了,我很尴尬地被困在这么简单的事情上,但我想改进!所以请帮助。流程出了什么问题?

编辑:尝试使用运算符,但结果似乎仍然不正确。

我的运营商代码:

struct //Compare : public std::binary_function<cv::Vec3b,cv::Vec3b,bool>
{
    bool operator()(cv::Vec3b &a, cv::Vec3b &b)
    {
         return std::tie(a[0], a[1], a[2]) < std::tie(b[0], b[1], b[2]); 
    }
}inOrder;

我用它作为排序函数的参数。

sort(temp.begin(), temp.end(),inOrder);

然而,结果仍然不理想,或者说似乎不正确。我是否错误地声明了运算符(operator)?我从这里得到了这个想法,http://en.cppreference.com/w/cpp/algorithm/sort , 在自定义函数对象下。

最佳答案

您的 mostCharmostCount 在每次迭代时都会重置,因此 mostChar 将始终是最后一个元素。

移动

mostChar = temp[z]; // replace by temp[0]
mostCount = 0;

在循环之外。

关于c++ - 查找出现次数最多的值(cv::Vec3b)结果似乎是错误的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22039090/

相关文章:

java - 具有不断变化的键值的优先级队列

c++ - 如何向模板类公开统一接口(interface)?

c++ - 将仿函数作为函数指针传递

python - 使用 opencv Python 删除图像的背景

c++ - 从网络摄像头迁移到 Raspicam 时 OpenCV 的颜色问题

c# - 检测图像中的圆形图案

python - 使用 Gstreamer 和 OpenCV 进行 RTSP 流传输 (Python)

c++ - 在 C++ 中实现工厂方法的首选方法是什么?

c++ - cURL:处理多个异步请求

visual-studio-2010 - 在Visual C++中比较图像和视频