1.引言
Canny算子是一种较为好用的边缘检测算子,边缘检测效果良好。利用Python实现,原速度约为5分钟以上,不能够满足使用需要。
本文利用Python实现,并注意使用numba支持的数据类型及写法进行,故而可以利用numba进行加速,对5000*3000像素图像提取边缘,整体流程用时13秒,满足使用需要。
2.预备功能函数
1.卷积函数
def convolution(image, kernel):
"""
This function is used for convolution.
Args:
image: image input.
kerbel: the filter.
"""
kernel_height, kernel_width = kernel.shape
height, width = image.shape
kernel_size = kernel_height
half_size = np.floor(kernel_size/2)
@numba.jit(nopython = True)
def conv(image, kernel, half_size, height, width):
result = np.zeros((height, width), dtype = np.float32)
for row in range(half_size, height - half_size):
for col in range(half_size, width - half_size):
sum_var = 0
for v_row in range(-1*half_size, half_size+1):
for v_col in range(-1*half_size, half_size+1):
sum_var = sum_var + image[row+v_row, col+v_col] * kernel[v_row, v_col]
result[row, col] = sum_var
return result
result = conv(image, kernel, half_size, height, width)
return result
2.高斯模板函数
用于提供一个高斯滤波核
def generate_Guassian_template(kernel_size = 3, sigma = 1):
template = np.zeros((kernel_size, kernel_size), \
dtype = np.float32)
halfsize = np.floor(kernel_size/2).astype(np.int16)
@numba.jit(nopython = True)
def gaussian2d(x, y, sigma):
result = np.exp(-(np.power(x, 2)+np.power(y, 2))/(2*np.power(sigma, 2)))
return result
@numba.jit(nopython = True)
def generate(template, halfsize, sigma):
for v_row in range(-1*halfsize, halfsize+1):
for v_col in range(-1*halfsize, halfsize+1):
template[v_row+halfsize, v_col+halfsize] = gaussian2d(v_ro

本文介绍了使用Python和numba库实现Canny边缘检测算子的优化过程,通过高斯滤波、梯度计算、非极大值抑制和双阈值检测等步骤,将处理5000*3000像素图像的时间从5分钟缩短到13秒。文章还提供了卷积、高斯模板、梯度计算等辅助函数的实现,并详细展示了关键步骤的代码。
最低0.47元/天 解锁文章
1万+





