C++ : Coin Detection Program using OpenCV

In this tutorial, you are going to learn how to detect coins in C++ programming language using the OpenCV library. Before getting to the code you must know what is OpenCV library and what is it used for.

About OpenCV library

OpenCV stands for Open Source Computer Vision. This library contains a set of functions that are mainly based on visualizing, understand and process images. It was launched in 1999 by Intel and supported by most of the OS.

Coin Detection Program using OpenCV using C++

Include Interface for capturing an image

#include <C:/ocv/opencv/build/include/opencv2/highgui/highgui.hpp>

Include Interface for Image Processing

#include <C:/ocv/opencv/build/include/opencv2/imgproc/imgproc.hpp>

Include header files for input and output

#include <iostream>
#include <stdio.h>

The namespace for CV and I/O operations

using namespace cv;
using namespace std;

Mat contains the image where the image is the object of Mat

int main()
    Mat image;

Read image from file


Coin variable of type vector to store details of Coins

vector coin;

HoughCircles function is to detect circles in an image

HoughCircles(image,coin,CV_HOUGH_GRADIENT,2,20,450,60,0,0 );

Get number of coins

int l=coin.size();

Print number of Coins

cout<<"\n The number of coins is: "<<l<<"\n\n";

To draw detected circles on the image

for (size_t i = 0; i < coin.size(); i++)
        Point center(cvRound(coin[i][0]), cvRound(coin[i][1]));
        int radius = cvRound(coin[i][2]);
        circle(image, center, 3, Scalar(0, 255, 0), -1, 8, 0);
        circle(image, center, radius, Scalar(0, 0, 255), 3, 8, 0);
        cout << " Center location for circle " << i + 1 << " :"<<center<<"\n Diameter : "<<2*radius<<"\n";

Window creation to show a processed image

 namedWindow("Image after processing",CV_WINDOW_AUTOSIZE);

To display the window created

imshow("Coin Counter",image);

To wait for keypress


At last return from the main function.

Return 0; }


This program was created using the Hough transform algorithm of circles.

Also read: Install OpenCV C++ with Visual Studio

Leave a Reply

Your email address will not be published. Required fields are marked *