OpenCV Python HoughCircles: Circles detected outside of image boundary -
OpenCV Python HoughCircles: Circles detected outside of image boundary -
i using opencv houghcircles
method in python follows:
circles = cv2.houghcircles(img,cv.cv_hough_gradient,1,20, param1=50,param2=30,minradius=0,maxradius=0)
this seems work quite well. however, 1 thing noticed detects circles can extend outside of image boundaries. know how can filter these results out?
think of each circle beingness bounded within square of dimensions 2r x 2r
r
radius of circle. also, centre of box located @ (x,y)
corresponds centre of circle located in image. see if circle within image boundaries, need create sure box contains circle not go outside of image. mathematically speaking, need ensure that:
r <= x <= cols-1-r r <= y <= rows-1-r # assuming 0-indexing
rows
, cols
rows , columns of image. have cycle through every circle in detected result , filter out circles go outside of image boundaries checking if centre of each circle within 2 inequalities specified above. if circle within 2 inequalities, save circle. circles don't satisfy inequalities, don't include in final result.
to set logic code, this:
import cv # load in relevant packages import cv2 import numpy np img = cv2.imread(...,0) # load in image here - ensure 8-bit grayscale final_circles = [] # stores final circles don't go out of bounds circles = cv2.houghcircles(img,cv.cv_hough_gradient,1,20,param1=50,param2=30,minradius=0,maxradius=0) # code rows = img.shape[0] # obtain rows , columns cols = img.shape[1] circles = np.round(circles[0, :]).astype("int") # convert integer (x, y, r) in circles: # each circle have detected... if (r <= x <= cols-1-r) , (r <= y <= rows-1-r): # check if circle within boundary final_circles.append([x, y, r]) # if is, add together our final list final_circles = np.asarray(final_circles).astype("int") # convert numpy array compatability
the peculiar thing cv2.houghcircles
returns 3d matrix first dimension singleton dimension. eliminate singleton dimension, did circles[0, :]
result in 2d matrix. each row of new 2d matrix contains tuple of (x, y, r)
, characterizes circle located in image radius. converted centres , radii integers if decide draw them later on, able cv2.circle
.
python opencv image-processing hough-transform
Comments
Post a Comment