# python数字图像处理（16）：霍夫圆和椭圆变换

x=x0+rcosθ

y=y0+rsinθ

import numpy as np
import matplotlib.pyplot as plt
from skimage import draw,transform,feature

img = 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,:] =255
img[cc1, rr1,:] =255

fig, (ax0,ax1) = plt.subplots(1,2, figsize=(8, 5))

ax0.imshow(img)  #显示原图
ax0.set_title('origin image')

hough_radii = np.arange(50, 80, 5)  #半径范围

centers = []  #保存所有圆心点坐标
accums = []   #累积值

#每一个半径值，取出其中两个圆
num_peaks = 2
peaks =feature.peak_local_max(h, num_peaks=num_peaks) #取出峰值
centers.extend(peaks)
accums.extend(h[peaks[:, 0], peaks[:, 1]])

#画出最接近的圆
image =np.copy(img)
for idx in np.argsort(accums)[::-1][:2]:
center_x, center_y = centers[idx]
image[cy, cx] =(255,0,0)

ax1.imshow(image)
ax1.set_title('detected image')

import numpy as np
import matplotlib.pyplot as plt
from skimage import data, color,draw,transform,feature,util

image = 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)  #半径范围

centers = []  #保存中心点坐标
accums = []   #累积值

#每一个半径值，取出其中两个圆
num_peaks = 2
peaks =feature.peak_local_max(h, num_peaks=num_peaks) #取出峰值
centers.extend(peaks)
accums.extend(h[peaks[:, 0], peaks[:, 1]])

#画出最接近的5个圆
image = color.gray2rgb(image)
for idx in np.argsort(accums)[::-1][:5]:
center_x, center_y = centers[idx]
image[cy, cx] = (255,0,0)

ax1.imshow(image)
ax1.set_title('detected image')

skimage.transform.hough_ellipse(img,accuracythreshold, min_sizemax_size)

img: 待检测图像。

accuracy: 使用在累加器上的短轴二进制尺寸，是一个double型的值，默认为1

thresh: 累加器阈值，默认为4

min_size: 长轴最小长度，默认为4

max_size: 短轴最大长度，默认为None,表示图片最短边的一半。

import matplotlib.pyplot as plt
from skimage import data,draw,color,transform,feature

#加载图片，转换成灰度图并检测边缘
image_rgb = data.coffee()[0:220, 160:420] #裁剪原图像，不然速度非常慢
image_gray = color.rgb2gray(image_rgb)
edges = feature.canny(image_gray, sigma=2.0, low_threshold=0.55, high_threshold=0.8)

#执行椭圆变换
result =transform.hough_ellipse(edges, accuracy=20, threshold=250,min_size=100, max_size=120)
result.sort(order='accumulator') #根据累加器排序

#估计椭圆参数
best = list(result[-1])  #排完序后取最后一个
yc, xc, a, b = [int(round(x)) for x in best[1:5]]
orientation = best[5]

#在原图上画出椭圆
cy, cx =draw.ellipse_perimeter(yc, xc, a, b, orientation)
image_rgb[cy, cx] = (0, 0, 255) #在原图中用蓝色表示检测出的椭圆

#分别用白色表示canny边缘，用红色表示检测出的椭圆，进行对比
edges = color.gray2rgb(edges)
edges[cy, cx] = (250, 0, 0)

fig2, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(8, 4))

ax1.set_title('Original picture')
ax1.imshow(image_rgb)

ax2.set_title('Edge (white) and result (red)')
ax2.imshow(edges)

plt.show()

posted @ 2016-01-26 13:36  denny402  阅读(...)  评论(...编辑  收藏