认为每个圆都被限制在一个尺寸为2r x 2r的正方形内,其中r是圆的半径.此外,此框的中心位于(x,y),该位置也对应于圆心在图像中的位置.要查看圆是否在图像边界之内,只需确保包含该圆的框不在图像的外面.从数学上来说,您需要确保:
r <= x <= cols-1-r
r <= y <= rows-1-r # Assuming 0-indexing
行和列是图像的行和列.现在,您真正要做的就是在检测结果中的每个圆圈之间循环,并通过检查每个圆圈的中心是否在上述两个不等式之内来滤除超出图像边界的圆圈.如果圆在两个不等式之内,则可以保存该圆.任何不满足不等式的圈子,都不要在最终结果中包括.
要将这种逻辑写入代码,请执行以下操作:
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
关于cv2.HoughCircles的特殊之处在于它返回一个3D矩阵,其中第一维是单例维.为了消除此单例维度,我做了circle [0,:],将生成2D矩阵.这个新的2D矩阵的每一行都包含一个(x,y,r)元组,并描述圆在图像中的位置及其半径.我还将中心和半径转换为整数,以便以后决定绘制它们时,可以使用cv2.circle进行处理.