Hough Circle Transform In Python – Detect Circle
In this tutorial, we will learn how to detect a circle in the Image in Python. After this tutorial, You will be able to use some important libraries and methods which will help you in the future.
What is Hough Circle detection?
Hough circle detection is a method to detect the circles in the image and video. This is very helpful to detect the circle.
In this tutorial, we will find circles in images using houghCircle()
method of openCV package in Python.
Installation Of Libraries
pip install opencv-python
pip install matplotlib
Python Program For Hough Circle Detection
First, we need to import our libraries cv2 module of OpenCV, Numpy and Matplotlib. After that, we have to read our image using imread()
function and copy the image in image2 variable for future use.
import cv2 import numpy as np # import matplotlib.pyplot as plt image = cv2.imread("imagefor.jpg") image2 = image.copy()
After that, we will be smoothing our image using medianBlur()
method by passing the image variable and kernel size. The next line converts our image BGR to gray using cvtColor()
function with parameters image and convert-type.
image = cv2.medianBlur(image,5) gray = cv2.cvtColor(image,code = cv2.COLOR_BGR2GRAY) circles = cv2.HoughCircles(gray,cv2.HOUGH_GRADIENT,1,20,param1=50,param2 =30,minRadius=0,maxRadius=0) hough_Circles = np.uint16(np.around(circles))
The below code helps us to detect all circles from the image and show them on our copy image. Here we use for loop to iterate through the image by three variables x,y, and z are coordinates and the radius of the circle.
In the code using circle()
method draw the circle on the image. The first method draws the circumference of the circle and the next method draws the center of the circle. The third argument of the circle is the RGB color format for the circumference and center of the circle.
for (x,y,z) in range[0:]: cv2.circle(gray,(x,y),r ,(255,0,0),3) cv2.circle(gray,(x,y),2,(0,0,255)) cv2.imshow("Hough Circles", gray) cv2.waitKey(0) cv2.destroyAllWindows()
Also read:
Leave a Reply