python opencv - blob detection or circle detection

心已入冬 提交于 2019-11-30 01:59:52

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.

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()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!