在极坐标中,圆的表示方式为:
x=x0+rcosθ
y=y0+rsinθ
圆心为(x0,y0),r为半径,θ为旋转度数,值范围为0-359
如果给定圆心点和半径,则其它点是否在圆上,我们就能检测出来了。在图像中,我们将每个非0像素点作为圆心点,以一定的半径进行检测,如果有一个点在圆上,我们就对这个圆心累加一次。如果检测到一个圆,那么这个圆心点就累加到最大,成为峰值。因此,在检测结果中,一个峰值点,就对应一个圆心点。
霍夫圆检测的函数:
skimage.transform.hough_circle(image, radius)
radius是一个数组,表示半径的集合,如[3,4,5,6]
返回一个3维的数组(radius index, M, N), 第一维表示半径的索引,后面两维表示图像的尺寸。
例1:绘制两个圆形,用霍夫圆变换将它们检测出来。
import numpy as npimport matplotlib.pyplot as pltfrom skimage import draw,transform,featureimg = np.zeros((250, 250,3), dtype=np.uint8)rr, cc = draw.circle_perimeter(60, 60, 50) #以半径50画一个圆rr1, cc1 = draw.circle_perimeter(150, 150, 60) #以半径60画一个圆img[cc, rr,:] =255img[cc1, rr1,:] =255fig, (ax0,ax1) = plt.subplots(1,2, figsize=(8, 5))ax0.imshow(img) #显示原图ax0.set_title('origin image')hough_radii = np.arange(50, 80, 5) #半径范围hough_res =transform.hough_circle(img[:,:,0], hough_radii) #圆变换 centers = [] #保存所有圆心点坐标accums = [] #累积值radii = [] #半径for radius, h in zip(hough_radii, hough_res): #每一个半径值,取出其中两个圆 num_peaks = 2 peaks =feature.peak_local_max(h, num_peaks=num_peaks) #取出峰值 centers.extend(peaks) accums.extend(h[peaks[:, 0], peaks[:, 1]]) radii.extend([radius] * num_peaks)#画出最接近的圆image =np.copy(img)for idx in np.argsort(accums)[::-1][:2]: center_x, center_y = centers[idx] radius = radii[idx] cx, cy =draw.circle_perimeter(center_y, center_x, radius) image[cy, cx] =(255,0,0)ax1.imshow(image)ax1.set_title('detected image')
结果图如下:原图中的圆用白色绘制,检测出的圆用红色绘制。
例2,检测出下图中存在的硬币。
import numpy as npimport matplotlib.pyplot as pltfrom skimage import data, color,draw,transform,feature,utilimage = util.img_as_ubyte(data.coins()[0:95, 70:370]) #裁剪原图片edges =feature.canny(image, sigma=3, low_threshold=10, high_threshold=50) #检测canny边缘fig, (ax0,ax1) = plt.subplots(1,2, figsize=(8, 5))ax0.imshow(edges, cmap=plt.cm.gray) #显示canny边缘ax0.set_title('original iamge')hough_radii = np.arange(15, 30, 2) #半径范围hough_res =transform.hough_circle(edges, hough_radii) #圆变换 centers = [] #保存中心点坐标accums = [] #累积值radii = [] #半径for radius, h in zip(hough_radii, hough_res): #每一个半径值,取出其中两个圆 num_peaks = 2 peaks =feature.peak_local_max(h, num_peaks=num_peaks) #取出峰值 centers.extend(peaks) accums.extend(h[peaks[:, 0], peaks[:, 1]]) radii.extend([radius] * num_peaks)#画出最接近的5个圆image = color.gray2rgb(image)for idx in np.argsort(accums)[::-1][:5]: center_x, center_y = centers[idx] radius = radii[idx] cx, cy =draw.circle_perimeter(center_y, center_x, radius) image[cy, cx] = (255,0,0)ax1.imshow(image)ax1.set_title('detected image')
新闻热点
疑难解答