Python+opencv 高斯滤波

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_gaussian_noise(image, sigma=20):
    img = image.astype(np.int16)  # 此步是为了避免像素点小于0,大于255的情况
    img_size = img.shape
    if len(img_size) == 3:
        x, y, z = img.shape
    else:
        x, y = img.shape
        z = 0
    mu = 0
    for i in range(x):
        for j in range(y):
            if img_size == 3:
                for k in range(z):
                    img[i, j, k] = img[i, j, k] + random.gauss(mu=mu, sigma=sigma)
            else:
                img[i, j] = img[i, j] + random.gauss(mu=mu, sigma=sigma)
    img[img > 255] = 255
    img[img < 0] = 0
    img = img.astype(np.uint8)
    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_gaussian_noise(source)  # 给原图添加高斯噪声
source_noise_gaussian_filter = cv2.GaussianBlur(source_noise, (5, 5), 0)
source_noise_average_filtering_5x5 = cv2.blur(source_noise, ksize=(5, 5))

imgs = [source,
        source_noise,
        source_noise_gaussian_filter,
        source_noise_average_filtering_5x5]
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()

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值