Circle and Line
Circle and Line
Circle detection finds a variety of uses in biomedical applications, ranging from iris
detection to white blood cell segmentation.
To detect circles, we may fix a point (x, y). Now, we are required to find 3 parameters: a,
b and r. Therefore, the problem is in a 3-dimensional search space. To find possible
circles, the algorithm uses a 3-D matrix called the “Accumulator Matrix” to store
potential a, b and r values.
The HoughCircles function in OpenCV has the following parameters which can be
altered according to the image.
Coding
import cv2
# Read image
img = cv2.imread(“image1.png”)
# Smooth it
img = cv2.medianBlur(img,3)
img_copy = img.copy()
# Convert to greyscale
img_gray = cv2.cvtColor(img_copy,cv2.COLOR_BGR2GRAY)
# Apply Hough transform to greyscale image
circles = cv2.HoughCircles(img_gray,cv2.HOUGH_GRADIENT,1,20,
param1=60,param2=40,minRadius=0,maxRadius=0)
circles = np.uint16(np.around(circles))
# Draw the circles
for (x,y,r ) in circles[0,:]:
# draw the outer circle
cv2.circle(img,(x,y),r,(0,255,0),3)
# draw the center of the circle
cv2.circle(img,(x,y),2,(0,255,0),3)
cv2.imshow('detected circles',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output:
Line Detection
The Hough Transform is a method that is used in image processing to detect any shape,
if that shape can be represented in mathematical form. It can detect the shape even if it
is broken or distorted a little bit.
Python Program
import cv2
import numpy as np
image = cv2.imread(“lines.jpg”)
gray=cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
canimg = cv2.Canny(gray,50,200)
lines = cv2.HoughLines(canimg, 1, np.pi/180, 120, np.array([]))
for line in lines:
Rho,theta = line[0]
a=np.cos(theta)
b=np.sin(theta)
x0=a*rho
y0=b*rho
x1=int(x0+1000*(-b))
y1=int(y0+1000*(a))
x2=int(x0-1000*(-b))
y2=int(y0-1000*(a))
cv2.line(image,(x1,y1),(x2,y2),(0,0,255),2)
cv2.imshow(image)
cv2.imshow(canimage)