- 图像模糊
图像模糊目的之一是为了图像预处理时降低图像噪声。图像的模糊通常利用卷积来实现。图像模糊以下几种常见的分别为:归一化均值滤波器(API:blur()),中值滤波器(meadian_blur():主要针对椒盐噪声)
blur(InputArray src,//输入图像,对通道是单独处理的
OutputArray dst,//输出图像
Size ksize,//内核的大小
Point anchor = Point(-1, -1),//默认,表示锚点在核的中心
int borderType = BORDER_DEFAULT)
import cv2
def blur_demo(image):
#dst
dst = cv2.blur(image,(5,5))
cv2.imshow('dst',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
#中值滤波
def meadian_blur_demo(image):
dst = cv2.medianBlur(image,5)
cv2.imshow('dst',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
#custom_blur
def custorm_blur_demo(image):
#均值模糊的kernel
kernel = np.ones([5,5],np.float32)/25
#锐化:数据增强Kernel:
kernel = np.array([[-1,1,-1],[-1,1,1],[-1,1,1]])#特点:9个数相加和为1
dst = cv2.filter2D(image,-1,kernel)
cv2.imshow('custorm_blur_demo',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
2.高斯模糊
#高斯噪声
def clamp(pv):
if pv>255:return 255
if pv<0:return 0
else: return pv
#创建噪声图片
def gausi_noise(image):
h,w,c = image.shape
dst = image.copy()
for row in range(h):
for col in range(w):
noise = np.random.normal(0,20,3)
b = clamp(image[row,col,0]+noise[0])
g = clamp(image[row,col,1]+noise[1])
r = clamp(image[row,col,2]+noise[2])
dst[row,col,0] = b
dst[row,col,1] = g
dst[row,col,2] = r
return dst
def gause_blur_demo(image):
#ksize和sigma设置一个即可
dst = cv2.GaussianBlur(image,(0,0),15)
cv2.imshow('dst_gauss',dst)
image = cv2.imread('zsl.jpg')
freq = cv2.getTickFrequency()
t1 = cv2.getTickCount()
dst = gausi_noise(image)
t2 = cv2.getTickCount()
print((t2-t1)/freq)
cv2.imshow('dst',dst)
gause_blur_demo(dst)
cv2.waitKey(0)
cv2.destroyAllWindows()