提示:内容整理自:https://github.com/gzr2017/ImageProcessing100Wen
CV小白从0开始学数字图像处理
Prewitt 滤波器是用于边缘检测的一种滤波器,使用下式定义:
(a)纵向 (b)横向
-1 -1 -1 -1 0 1
K = [ 0 0 0 ] K = [ -1 0 1 ]
1 1 1 -1 0 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 Filter
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., -1., -1.],[0., 0., 0.], [1., 1., 1.]]
## Sobel horizontal
#K = [[-1., 0., 1.],[-1., 0., 1.],[-1., 0., 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 滤波器处理后结果
左:垂直
右:水平
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)