OpenCV  3.1.0-dev
Open Source Computer Vision
Hough Circle Transform

Goal

In this chapter,

Theory

A circle is represented mathematically as \((x-x_{center})^2 + (y - y_{center})^2 = r^2\) where \((x_{center},y_{center})\) is the center of the circle, and \(r\) is the radius of the circle. From equation, we can see we have 3 parameters, so we need a 3D accumulator for hough transform, which would be highly ineffective. So OpenCV uses more trickier method, Hough Gradient Method which uses the gradient information of edges.

The function we use here is cv2.HoughCircles(). It has plenty of arguments which are well explained in the documentation. So we directly go to the code.

1 import cv2
2 import numpy as np
3 
4 img = cv2.imread('opencv_logo.png',0)
5 img = cv2.medianBlur(img,5)
6 cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
7 
8 circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20,
9  param1=50,param2=30,minRadius=0,maxRadius=0)
10 
11 circles = np.uint16(np.around(circles))
12 for i in circles[0,:]:
13  # draw the outer circle
14  cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
15  # draw the center of the circle
16  cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)
17 
18 cv2.imshow('detected circles',cimg)
19 cv2.waitKey(0)
20 cv2.destroyAllWindows()

Result is shown below:

houghcircles2.jpg
image

Additional Resources

Exercises