Common image filtering operations are:
Mean filter (cv2.blur)
box filter (cv2.boxFilter)
Gaussian filter (cv2.GaussianBlur)
median filter (cv2.medianBlur)
bilateral filter (cv2.bilateralFilter)
sample code
import cv2
import matplotlib.pyplot as plt
import numpy as np
img = cv2.imread("C:\\Users\\zhangqs\\Desktop\\dog.png", cv2.IMREAD_COLOR)
def cv_show(name, img):
cv2.imshow(name, img) # 显示图像
cv2.waitKey(0) # 等待时间,单位毫秒,0表示任意键终止
cv2.destroyAllWindows()
# 在图片上生成椒盐噪声
def add_peppersalt_noise(image, n=10000):
result = image.copy()
# 测量图片的长和宽
w, h =image.shape[:2]
# 生成n个椒盐噪声
for i in range(n):
x = np.random.randint(1, w)
y= np.random.randint(1, h)
if np.random.randint(0, 2) == 0 :
result[x, y] = 0
else:
result[x,y] = 255
return result
imgnoise = add_peppersalt_noise(img)
#1.均值滤波-简单的平均卷积操作
blur=cv2.blur(img,(3,3)) #卷积核大小3*3,中间像素点=9个像素点和/9,卷积核大小一般都是奇数
#2.方框滤波-基本和均值一样,可以选择归一化
box=cv2.boxFilter(img,-1,(3,3),normalize=True)
#3.高斯滤波
gaussian=cv2.GaussianBlur(img,(5,5),1)
#4.中值滤波
median=cv2.medianBlur(img,5)
#5.双边滤波
bilateral = cv2.bilateralFilter(img, 9, 150, 150)
#合并显示
res=np.hstack((img,imgnoise,blur,gaussian,median,bilateral)) #注意:两层括号
cv2.imshow('all',res)
cv2.waitKey(0)
cv2.destroyAllWindows()
running result
For a more detailed explanation, you can refer to the following link:
Image filtering of Opencv: 2. Mean filtering (cv2.blur)_Justth.'s Blog-CSDN Blog
Image filtering of Opencv: 3. Box filtering (cv2.boxFilter)_Justth.'s Blog-CSDN Blog
Image filtering of Opencv: 4. Gaussian filtering (cv2.GaussianBlur)_Justth.'s Blog-CSDN Blog
Image filtering of Opencv: 6. Bilateral filtering (cv2.bilateralFilter)_Justth.'s blog - CSDN blog