In this project we are going to implement Coin Detection algorithm in OpenCV Python. We are going to use real time webcam feed for detecting the coins. We created a simulated lab bench environment where we tested our algorithm. Similar code could be used in Raspberry PI as well. So if you installed the OpenCV in Raspberry Pi you can use same code to implement a coin detection code in the raspberry pi as well.

Coin Detection Code

Here is the complete code for the coin detection in Python using OpenCV library. We used the Hough Circle algorithm for circle identification later we created some threshold value for detecting the circle of the size of our coin. We then segment the image and fetch those circle using contour analysis in OpenCV Python. If you want to learn more about the contour detection you can check one of my previous post about contour detection in OpenCV Python where I discussed this in detail.

Python Coin detection using hough circles in OpenCV Python live demo

Here is the code

import cv2
import numpy as np

cap = cv2.VideoCapture(1)

  # Capture frame-by-frame
  ret, frame =
  if ret:
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    circles = cv2.HoughCircles(gray, 3, 1.2, 100)
      # ensure at least some circles were found
    if circles is not None:
      # convert the (x, y) coordinates and radius of the circles to integers
      circles = np.round(circles[0, :]).astype("int")
      # loop over the (x, y) coordinates and radius of the circles
      for (x, y, r) in circles:
          # draw the circle in the output image, then draw a rectangle
          # corresponding to the center of the circle
, (x, y), r, (0, 255, 0), 4)
          cv2.rectangle(frame, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
      # show the output image
    #cv2.imshow("output", np.hstack([image, output]))
    if cv2.waitKey(1) & 0xFF == ord('q'):
      print('no frame')
# When everything done, release the capture

Code language: Python (python)

By Abdul Rehman

My name is Abdul Rehman and I love to do Reasearch in Embedded Systems, Artificial Intelligence, Computer Vision and Engineering related fields. With 10+ years of experience in Research and Development field in Embedded systems I touched lot of technologies including Web development, and Mobile Application development. Now with the help of Social Presence, I like to share my knowledge and to document everything I learned and still learning.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.