OpenCV Python HoughCircles: circles detected outside image border

I am using OpenCV method HoughCircles

in Python like this:

circles = cv2.HoughCircles(img,cv.CV_HOUGH_GRADIENT,1,20,
param1=50,param2=30,minRadius=0,maxRadius=0)

      

This seems to work pretty well. However, I noticed that it detects circles that can extend beyond the borders of the image. Does anyone know how I can filter these results?

+3


source to share


2 answers


Think of each circle being constrained within a size square 2r x 2r

, where r

is the radius of the circle. In addition, the center of this box is at (x,y)

, which also corresponds to where the center of the circle is in the image. To see if the circle is inside the borders of the image, you just need to make sure that the box containing the circle does not go beyond the borders of the image. Mathematically speaking, you need to make sure that:

r <= x <= cols-1-r
r <= y <= rows-1-r # Assuming 0-indexing

      

rows

and cols

are the rows and columns of your image. All you really need to do is loop through each circle in the detected result and filter out those circles that go beyond the bounds of the image, checking if the center of each circle is in the above two inequalities. If the circle is within two inequalities, you keep that circle. Any circles that do not satisfy the inequalities are not included in the final result.



To put this logic in your code, do something like this:

import cv # Load in relevant packages
import cv2
import numpy as np

img = cv2.imread(...,0) # Load in image here - Ensure 8-bit grayscale
final_circles = [] # Stores the final circles that don't go out of bounds
circles = cv2.HoughCircles(img,cv.CV_HOUGH_GRADIENT,1,20,param1=50,param2=30,minRadius=0,maxRadius=0) # Your code
rows = img.shape[0] # Obtain rows and columns
cols = img.shape[1]
circles = np.round(circles[0, :]).astype("int") # Convert to integer
for (x, y, r) in circles: # For each circle we have detected...
    if (r <= x <= cols-1-r) and (r <= y <= rows-1-r): # Check if circle is within boundary
        final_circles.append([x, y, r]) # If it is, add this to our final list

final_circles = np.asarray(final_circles).astype("int") # Convert to numpy array for compatability

      

The peculiarity cv2.HoughCircles

is that it returns a three-dimensional matrix, where the first dimension is solid. To eliminate this single element dimension I did circles[0, :]

which would result in a 2D matrix. Each row of this new 2D matrix contains a tuple (x, y, r)

and characterizes where the circle is in your image, as well as its radius. I also converted the centers and radii to integers, so if you decide to draw them later, you can do it with cv2.circle

.

+4


source


you can add a function that will take the center and the radius of the circle will add them / and subtract and check if this will lead outside of your image.



0


source







All Articles