【Python】sobel卷积滤波器实现图像边缘检测

有关卷积filter

索贝尔卷积核

Sobel 算子 也叫 Sobel 滤波, 是两个 3*3 的矩阵, 主要用来计算图像中某一点在横向/纵向上的梯度
Sobel 算子 有两个滤波矩阵:Gx 和 Gy, Gx 用来计算横向的梯度,Gy 用来计算纵向的梯度
注意:这里列出的这两个梯度矩阵对应于横向从左到右(x轴),纵向从上到下的坐标轴(y轴)

需要注意的几点

边缘检测时 所有元素总和为 0 是很重要的。因为这类过滤器要计算的是相邻像素的差异 或者说变化,要计算差异 就需要将像素值相减。在这个例子中
我们要将中间像素与周围像素的值相减,如果这些核值加起来不等于
0,那就意味着计算出来的差,权重会有正负,结果就是滤波后的图像亮度会相应地提高或或降低

作者:徐凯_xp
来源:简书

Python实现

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pylab


def convolve(img,fill):
    rgb_r = img[:,:,0]
    rgb_g = img[:,:,1]
    rgb_b = img[:,:,2]

    pro_rgb_r = pre_convolve(rgb_r,fill)
    pro_rgb_g = pre_convolve(rgb_g,fill)
    pro_rgb_b = pre_convolve(rgb_b,fill)

    img_pro = np.dstack((pro_rgb_r,pro_rgb_g,pro_rgb_b))
    return img_pro


def pre_convolve(img,fill):
    fill_height = fill.shape[0]
    fill_width = fill.shape[1]

    img_height = img.shape[0]
    img_width = img.shape[1]

    img_pro_height = img_height - fill_height + 1
    img_pro_width = img_width - fill_width + 1

    pro_rgb = np.zeros((img_pro_height,img_pro_width),dtype='uint8')

    for i in range(img_pro_height):
        for j in range(img_pro_width):
            pro_rgb[i][j] = pro_statistic(img[i:i + fill_height,j:j + fill_width],fill)
    return pro_rgb


def pro_statistic(img,fill):
    res = (img * fill).sum()
    if(res > 255):
        res = 255
    elif(res < 0):
        res = abs(res)  # 让负边缘也显现出来
    return res


sobel_y = np.array([[-1,0,1],
                 [-2,0,2],
                 [-1,0,1]])  # 索贝尔算子 边缘检测

sobel_x = np.array([[-1,-2,-1],
                [0,0,0],
                [1,2,1]])


img = mpimg.imread('library.jpg')
res1 = convolve(img,sobel_x)
res2 = convolve(img,sobel_y)
res = res1 + res2
plt.imshow(res1)
plt.show()

plt.imshow(res2)
plt.show()

plt.imshow(res)
plt.show()

效果图

水平方向边缘检测:
在这里插入图片描述
竖直方向边缘检测
在这里插入图片描述
两者叠加最终效果图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Greif_Hairline

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值