链接: Circular and Elliptical Hough Transforms.
最简单形式的霍夫变换是一种检测直线的方法,但它也可用于检测圆或椭圆。该算法能够检测到边缘并且它能减少噪声或缺失点的发生。
圆检测
在以下示例中,霍夫变换用于检测硬币位置并匹配它们的边缘。我们提供了一系列合理的半径。对于每个半径,提取两个圆,我们最终保留五个最突出的候选者。结果表明硬币位置被很好地检测到。
算法概述
给定一个白色背景上的黑色圆圈,我们首先猜测它的半径(或半径范围)以构建一个新的圆圈。这个圆圈应用在原始图片的每个黑色像素上,这个圆圈的坐标在一个累加器中投票。
从这个几何结构中,原始圆心位置获得最高分。
请注意,累加器大小构建为大于原始图片,以便检测帧外的中心。它的尺寸是较大半径的两倍。
import numpy as np
import matplotlib.pyplot as plt
from skimage import data, color
from skimage.transform import hough_circle, hough_circle_peaks
from skimage.feature import canny
from skimage.draw import circle_perimeter
from skimage.util import img_as_ubyte
# Load picture and detect edges
image = img_as_ubyte(data.coins()[160:230, 70:270])
edges = canny(image, sigma=3, low_threshold=10, high_threshold=50)
# Detect two radii
hough_radii = np.arange(20, 35, 2)
hough_res = hough_circle(edges, hough_radii)
# Select the most prominent 3 circles
accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii,
total_num_peaks=3)
# Draw them
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 4))
image = color.gray2rgb(image)
for center_y, center_x, radius in zip(cy, cx, radii):
circy, circx = circle_perimeter(center_y, center_x, radius,
shape=image.shape)
image[circy, circx] = (220, 20, 20)
ax.imshow(image, cmap=plt.cm.gray)
plt.show()
椭圆概述
在第二个示例中,目的是检测咖啡杯的边缘。
基本上,这是圆的投影,即椭圆。
要解决的问题要困难得多,因为必须确定五个参数,而不是圆的三个参数。
算法概述
该算法采用属于椭圆的两个不同点。
它假定它是主轴。
所有其他点上的循环决定了椭圆传递给它们的程度。
良好的匹配对应于高累加器值。
import matplotlib.pyplot as plt
from skimage import data, color, img_as_ubyte
from skimage.feature import canny
from skimage.transform import hough_ellipse
from skimage.draw import ellipse_perimeter
# Load picture, convert to grayscale and detect edges
image_rgb = data.coffee()[0:220, 160:420]
image_gray = color.rgb2gray(image_rgb)
edges = canny(image_gray, sigma=2.0,
low_threshold=0.55, high_threshold=0.8)
# Perform a Hough Transform
# The accuracy corresponds to the bin size of a major axis.
# The value is chosen in order to get a single high accumulator.
# The threshold eliminates low accumulators
result = hough_ellipse(edges, accuracy=20, threshold=250,
min_size=100, max_size=120)
result.sort(order='accumulator')
# Estimated parameters for the ellipse
best = list(result[-1])
yc, xc, a, b = [int(round(x)) for x in best[1:5]]
orientation = best[5]
# Draw the ellipse on the original image
cy, cx = ellipse_perimeter(yc, xc, a, b, orientation)
image_rgb[cy, cx] = (0, 0, 255)
# Draw the edge (white) and the resulting ellipse (red)
edges = color.gray2rgb(img_as_ubyte(edges))
edges[cy, cx] = (250, 0, 0)
fig2, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(8, 4),
sharex=True, sharey=True)
ax1.set_title('Original picture')
ax1.imshow(image_rgb)
ax2.set_title('Edge (white) and result (red)')
ax2.imshow(edges)
plt.show()