提示:内容整理自:https://github.com/gzr2017/ImageProcessing100Wen
CV小白从0开始学数字图像处理
15 Sobel 滤波器
Sobel 滤波器可以提取特定方向的边缘,滤波器按下式定义:
(a)纵向 (b)横向
1 0 -1 1 2 1
K = [ 2 0 -2 ] K = [ 0 0 0 ]
1 0 -1 -1 -2 -1
代码如下:
1.引入库
CV2计算机视觉库
import cv2
import numpy as np
2.读入数据
img = cv2.imread("imori.jpg").astype(np.float)
H, W, C = img.shape
b = img[:, :, 0].copy()
g = img[:, :, 1].copy()
r = img[:, :, 2].copy()
3.灰度化
gray = 0.2126 * r + 0.7152 * g + 0.0722 * b
gray = gray.astype(np.uint8)
4.Sobel 滤波器
K_size = 3
5.边缘补0
pad = K_size // 2
out = np.zeros((H + pad*2, W + pad*2), dtype=np.float)
out[pad:pad+H, pad:pad+W] = gray.copy().astype(np.float)
tmp = out.copy()
6 vertical or horizontal
## Sobel vertical
K = [[1., 0., -1.],[2., 0., -2.],[1., 0., -1.]]
## Sobel horizontal
#K = [[1., 2., 1.],[0., 0., 0.], [-1., -2., -1.]]
7.处理
for y in range(H):
for x in range(W):
out[pad+y, pad+x] = np.sum(K * (tmp[y:y+K_size, x:x+K_size]))
out[out < 0] = 0
out[out > 255] = 255
out = out[pad:pad+H, pad:pad+W].astype(np.uint8)
8.保存结果
cv2.imwrite("out.jpg", out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
9.Sobel 滤波器处理后结果
左:垂直
右:水平