Find circles and ellipses in an image using OpenCV | python



OpenCV provides a convenient way to detect blobs and filter them based on various characteristics. There are various parameters that control the identification process and results. Important parameters used for this project:

  • Filter by area — this avoids any small dots present in the image that could be mistakenly detected in the form of a circle. 
  • Roundness filter — this helps us determine shapes that look more like a circle.
     Circularity =  

    A true circle has a roundness of 1, a square has a roundness of about 78%. 

  • Bulge filter — concavity in general, destroys roundness. The larger the bulge, the closer it is to the close circle. 
  • Inertia filter — objects similar to circle, have great inertia. For example, for a circle this value is 1, for an ellipse it is between 0 and 1, and for a line — 0. To filter by inertia coefficient, set filterByInertia = 1, and set 0 & lt; = minInertiaRatio & lt; = 1 and maxInertiaRatio (& lt; = 1) respectively. 

Below is the code for identifying circles:

import cv2

import numpy as np

 
# Upload image

image = cv2.imread ( `, 0 )

 
# Set our filtering options
# Initialize setting options using cv2.SimpleBlobDetector

params = cv2.SimpleBlobDetector_Params ()

 
# Set area filtering options

params.filterByArea = True

params. minArea = 100

  
# Set filtering parameters in a circle

params.filterByCircularity = True  

params.minCircularity = 0.9

 
# Set bump filtering options

 params.filterByConvexity = True

params. minConvexity = 0.2

  
# Set inertial filtering parameters

params.filterByInertia = True

params.minInertiaRatio = 0.01

 
# Create a detector with parameters

detector = cv2.SimpleBlobDetector_create (params)

 
# Detect blobs

keypoints = detector.detect (image)

 
# Draw blobs on our image as red circles

blank = np.zeros (( 1 , 1 )) 

blobs = cv2.drawKeypoints (image, keypoints, blank, ( 0 , 0 , 255 ),

  cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

 

number_of_blobs = len (keypoints)

text = " Number of Circular Blobs: " + str ( len (keypoints))

cv2.putText (blobs, text, ( 20 , 550 ),

cv2.FONT_HERSHEY_SIMPLEX, 1 , ( 0 , 100 , 255 ), 2 )

 
# Show Blobs

cv2.imshow ( "Filtering Circular Blobs Only" , blobs)

cv2.waitKey ( 0 )

cv2.destroyAllWindows ()

Output: