Skip to content Skip to sidebar Skip to footer

Python Opencv - Blob Detection Or Circle Detection

I am having problems detecting circle areas. I tried it with the HoughCircles function from opencv. However even though the images are pretty similar the parameters for the funtion

Solution 1:

As a starting point you may start with:

  • Find all the contours in the given image using cv2.findContours()
  • Iterate over each contour:
    • calculate the area, if the area of contour is in a given range say 70 < area < 150. This will filter out some extremely smaller and large contours.
    • After filtering the contours with the area threshold, you need to check the number of edges of contour, which can be done using: cv2.approxPolyDP(), for a circle len(approx) must be > 8 but < 23. Or you may apply some more sophisticated operations to detect circles here.

You should try to implement this approach and update the question with the code that you will write henceforth.

EDIT: As suggested by @Miki, there is a better and cleaner way of detecting if a geometrical shape is of circular shape using circularity = 4pi(area/perimeter^2), and decide a threshold such as 0.9, to check if the shape is circular. For perfect circle circularity == 1. You may fine tune this threshold as per your needs.

You may consult arcLength to find the perimeter of the contour and contourArea to get the area of the contour which are required to calculate the circularity.


Solution 2:

We could try Hough Transformation too to detect the circles in the image and play with the thresholds to get the desired result (detected circles in green boundary lines with red dots as centers):

import cv2
import numpy as np

img = cv2.imread('rbv2g.jpg',0)
img = cv2.medianBlur(img,5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,10,
                            param1=50,param2=12,minRadius=0,maxRadius=20)

circles = np.uint16(np.around(circles))
for i in circles[0,:]:
    # draw the outer circle
    cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
    # draw the center of the circle
    cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)

cv2.imshow('detected circles',cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()

enter image description here


Post a Comment for "Python Opencv - Blob Detection Or Circle Detection"