import cv2
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import random
# 设置画图支持中文
font = {'family': 'SimHei', 'size': 6}
matplotlib.rc('font', **font)
def add_noise(image, noise_num):
''' 添加椒盐噪声
:param image: 待添加噪声的图像
:param noise_num: 需要添加的噪声数量
:return: 添加噪声后的图像
'''
import copy
img = copy.deepcopy(image)
img_size = img.shape
rows, cols = img_size[0], img_size[1]
for i in range(noise_num):
x = np.random.randint(0, rows)
y = np.random.randint(0, cols)
if len(img_size) > 2: # if判断是彩图还是灰度图
if random.random() > 0.5:
img[x, y, :] = 255
else:
img[x, y, :] = 0
else:
if random.random() > 0.5:
img[x, y] = 255
else:
img[x, y] = 0
return img
# 图像路径
img_path = 'lenna.bmp'
# 按三通道图像格式读入
source = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)
if len(source.shape) > 2: # 彩图显示到plt上需要将BGR转为RGB
source = cv2.cvtColor(source, cv2.COLOR_BGR2RGB)
source_noise = add_noise(source, 10000)
source_noise_average_filtering = cv2.blur(source_noise, ksize=(3, 3))
source_noise_gaussian_filter = cv2.GaussianBlur(source_noise, (3, 3), 0)
source_noise_median_filter = cv2.medianBlur(source_noise, ksize=3)
imgs = [source_noise,
source_noise_average_filtering,
source_noise_gaussian_filter,
source_noise_median_filter]
titles = ['噪声图',
'噪声图均值滤波',
'噪声图高斯滤波',
'噪声图中值滤波']
for idx in range(len(imgs)):
plt.subplot(1, 4, idx + 1) # 1行4列,将图像放置在第idx+1位置上(从左往右,从上到下计数)
plt.imshow(imgs[idx], cmap='gray')
plt.title(titles[idx])
plt.axis('off')
# 保存图像,bbox_inches='tight'去除边缘空白,dpi设置图像清晰度
plt.savefig('中值滤波.png', bbox_inches='tight', dpi=300)
plt.show()
Python+opencv 中值滤波
最新推荐文章于 2024-08-09 14:43:38 发布