Canny算子的Python实现

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

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
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值