Prewitt 滤波器对图像进行边缘检测

一. Prewitt滤波器简介

        Prewitt是一种常用的检测图像边缘的滤波器,它分为横向和纵向算子,分别用于检测纵向和横向的边缘(注意:横向形式的滤波器检测图像的纵向边缘,纵向形式的滤波器检测图像的横向边缘)。


横向Prewitt滤波器(检测纵向边缘) ↑
 

纵向Prewitt滤波器(检测横向边缘) ↑
 

二. Prewitt滤波器和Sobel滤波器比较

        注意比较记忆 Prewitt 滤波器和 Sobel 滤波器,它们在形式和功能上十分相近,Sobel滤波器的算子如下两图:


Sobel 纵向算子,提取图像横向边缘 ↑  
 

Sobel 横向算子,提取图像纵向边缘 ↑
 

三. 实验:实现 Prewitt 算子并用算子对图像进行边缘检测

 1 import cv2
 2 
 3 import numpy as np
 4 
 5 # prewitt filter
 6 
 7 def prewitt_filter(img, K_size=3):
 8 
 9     H, W = img.shape
10 
11     # Zero padding
12 
13     pad = K_size // 2
14 
15     out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float)
16 
17     out[pad: pad + H, pad: pad + W] = img.copy().astype(np.float)
18 
19     tmp = out.copy()
20 
21     out_v = out.copy()
22 
23     out_h = out.copy()
24 
25     ## prewitt vertical kernel
26 
27     Kv = [[-1., -1., -1.],[0., 0., 0.], [1., 1., 1.]]
28 
29     ## prewitt horizontal kernel
30 
31     Kh = [[-1., 0., 1.],[-1., 0., 1.],[-1., 0., 1.]]
32 
33     # filtering
34 
35     for y in range(H):
36 
37         for x in range(W):
38 
39             out_v[pad + y, pad + x] = np.sum(Kv * (tmp[y: y + K_size, x: x + K_size]))
40 
41             out_h[pad + y, pad + x] = np.sum(Kh * (tmp[y: y + K_size, x: x + K_size]))
42 
43     out_v = np.clip(out_v, 0, 255)
44 
45     out_h = np.clip(out_h, 0, 255)
46 
47     out_v = out_v[pad: pad + H, pad: pad + W].astype(np.uint8)
48 
49     out_h = out_h[pad: pad + H, pad: pad + W].astype(np.uint8)
50 
51     return out_v, out_h
52 
53 # Read Gray image
54 
55 img = cv2.imread("../paojie_g.jpg",0).astype(np.float)
56 
57 # prewitt filtering
58 
59 out_v, out_h = prewitt_filter(img, K_size=3)
60 
61 # Save result
62 
63 cv2.imwrite("out_v.jpg", out_v)
64 
65 cv2.imshow("result_v", out_v)
66 
67 cv2.imwrite("out_h.jpg", out_h)
68 
69 cv2.imshow("result_h", out_h)
70 
71 cv2.waitKey(0)
72 
73 cv2.destroyAllWindows()

 


四. 实验结果:


原图 ↑
 

Prewitt 横向算子滤波结果(过滤得到纵向边缘) ↑
 

Prewitt 纵向算子滤波结果(过滤得到横向边缘) ↑
 

        我同时用同样大小的 Sobel算子 对同样图像进行了边缘检测,结果如下:


Sobel 横向算子滤波结果(过滤得到纵向边缘) ↑  
 

Sobel 纵向算子滤波结果(过滤得到横向边缘) ↑    
 

        从实验结果,我们可以观察到,对比使用 Sobel算子 和 Prewitt算子 进行图像边缘检测 ,Sobel滤波器能够获得更加清晰明亮的边缘。


五. 参考内容:

  https://www.jianshu.com/p/53ac8ffda399

posted on 2020-03-16 17:38  我坚信阳光灿烂  阅读(1441)  评论(0编辑  收藏  举报

导航