使用OpenCV计数硬币

我一直在尝试开发一个用C ++编写并使用OpenCV编写的程序,该程序对某些图像中显示的硬币的整体价值进行计数。 我应该注意,我是opencv平台的新手。

据我所知,为了实现这一目标,必须使用霍夫变换来检测硬币的比率。我在OpenCV网站上找到了此代码示例,但是我无法为硬币设置值。

这是我到目前为止所做的。

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>

using namespace std;
using namespace cv;
namespace
{

    const std::string windowName = "Coins detection";
    const std::string cannyThresholdTrackbarName = "Canny threshold";
    const std::string accumulatorThresholdTrackbarName = "accumulator Threshold";


    const int cannyThresholdInitialValue = 41;
    const int accumulatorThresholdInitialValue = 87;
    const int maxaccumulatorThreshold = 200;
    const int maxCannyThreshold = 255;

    void HoughDetection(const Mat& src_gray,const Mat& src_display,int cannyThreshold,int accumulatorThreshold)
    {

        std::vector<Vec3f> circles;

        HoughCircles( src_gray,circles,HOUGH_GRADIENT,1,src_gray.rows/8,cannyThreshold,accumulatorThreshold,0 );


        Mat display = src_display.clone();
        for( size_t i = 0; i < circles.size(); i++)
        {
            Point center(cvRound(circles[i][0]),cvRound(circles[i][1]));
            int radius = cvRound(circles[i][2]);



            circle( display,center,3,Scalar(0,255,0),-1,8,0 );

            circle( display,radius,255),0 );

        }


        imshow( windowName,display);
    }
}


int main(int argc,char** argv)
{
    Mat src,src_gray;


    String imageName("c:\\moedas.jpg");
    if (argc > 1)
    {
       imageName = argv[1];
    }
    src = imread( imageName,IMREAD_COLOR );

    if( src.empty() )
    {
        std::cerr<<"Invalid input image\n";

        return -1;
    }


    cvtColor( src,src_gray,COLOR_BGR2GRAY );


    GaussianBlur( src_gray,Size(9,9),2,2 );


    int cannyThreshold = cannyThresholdInitialValue;
    int accumulatorThreshold = accumulatorThresholdInitialValue;


    namedwindow( windowName,WINDOW_AUTOSIZE );
    createTrackbar(cannyThresholdTrackbarName,windowName,&cannyThreshold,maxCannyThreshold);
    createTrackbar(accumulatorThresholdTrackbarName,&accumulatorThreshold,maxaccumulatorThreshold);


    char key = 0;
    while(key != 'q' && key != 'Q')
    {

        cannyThreshold = std::max(cannyThreshold,1);
        accumulatorThreshold = std::max(accumulatorThreshold,1);


        HoughDetection(src_gray,src,accumulatorThreshold);


        key = (char)waitKey(10);
    }

    return 0;
}
heculestong 回答:使用OpenCV计数硬币

到目前为止,您在输入图像中仅具有圆形的代码。这只是计数硬币的第一步步骤。从简单的轮廓计数技术到复杂的深度学习,有许多方法来执行该任务,并且此类技术的解释范围太广,范围太大,无法有效,简洁地提出SO答案。但是,这里有一些您可以检查的硬币探测器/计数器实现/教程:

  • Implementation 1 in Python。这是列表中最好的,尽管代码文件比您的大,但移植到C ++并不难。它具有最佳的检测/计数性能,但可以处理神经网络,特别是多层感知器。

  • Implementation 2 in Python。这是一个非常小的代码文件,几乎与您的文件大小一样大,并且没有惯用的Python代码,因此将其移植到C ++完全是您的明智之举,您应该从此处开始。此实现借助Canny边缘检测器仅使用轮廓计数。

  • Tutorial 1 in C++。一个简单的C ++教程,但仅用于介绍性目的,上面列出的实现是真实的。

本文链接:https://www.f2er.com/3127009.html

大家都在问