In this Python OpenCV article iam going to talk about Circle Detection With HoughCircles.
OpenCV also has a function for detecting circles, called HoughCircles. It works in a very
similar fashion to HoughLines, but where minLineLength and maxLineGap were the
parameters to discard or retain lines, HoughCircles has a minimum distance between
circles’ centers, minimum, and maximum radius of the circles. Here’s the obligatory.
Also you can check Python GUI Development Tutorials in the below link.
1: PyQt5 GUI Development Tutorials
2: TKinter GUI Development Tutorials
3: Pyside2 GUI Development Tutorials
4: Kivy GUI Development Tutorials
So now this is the complete source code for this artilcle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import cv2 import numpy as np planets = cv2.imread('planet.jpg') gray_img = cv2.cvtColor(planets, cv2.COLOR_BGR2GRAY) img = cv2.medianBlur(gray_img, 5) cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR) #center circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,120,param1=100,param2=30,minRadius=0,maxRadius=0) circles = np.uint16(np.around(circles)) for i in circles[0,:]: # draw the outer circle cv2.circle(planets,(i[0],i[1]),i[2],(0,255,0),6) # draw the center of the circle cv2.circle(planets,(i[0],i[1]),2,(0,0,255),3) cv2.imshow("HoughCirlces", planets) cv2.waitKey() cv2.destroyAllWindows() |
Also you need to have an image in your working directory, iam using this image.
OK at the top code first we have loaded our image and have done some conversion to the image.
1 2 3 4 |
planets = cv2.imread('planet.jpg') gray_img = cv2.cvtColor(planets, cv2.COLOR_BGR2GRAY) img = cv2.medianBlur(gray_img, 5) cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR) |
So this is our HoughCircle algorithm for circle detection, it needs some parameters like input image, dp, minDistance, minRadious and maxRadious
1 |
circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,120,param1=100,param2=30,minRadius=0,maxRadius=0) |
OK now this line of code is for drawing two circles, an outer big circle and a inner small circle.
1 2 3 4 5 |
for i in circles[0,:]: # draw the outer circle cv2.circle(planets,(i[0],i[1]),i[2],(0,255,0),6) # draw the center of the circle cv2.circle(planets,(i[0],i[1]),2,(0,0,255),3) |
And this is for showing of our image.
1 2 3 |
cv2.imshow("HoughCirlces", planets) cv2.waitKey() cv2.destroyAllWindows() |
So now run the complete code and this will be the result
Also Watch the complete video for this article