Python3+OpenCV3+Pycharm编程:添加高斯噪声与高斯模糊

高斯模糊:高斯滤波是一种线性平滑低通滤波器,适用于消除高斯噪声,广泛应用于图像处理的减噪过程。滤波高斯就是对整幅图像进行加权平均的过程,每一个像素点的值,都由其本身和邻域内的其他像素值经过加权平均后得到。用一个模板(或称卷积,掩模)扫描图像中的每一个像素,用模板确定的邻域内像素的加权平均灰度值去替代模板中心像素点的值。

添加高斯噪声

def clamp(pv):
    """防止溢出"""
    if pv > 255:
        return 255
    elif pv < 0:
        return 0
    else:
        return pv


def gaussian_noise_demo(image):
    """添加高斯噪声"""
    h, w, c = image.shape
    for row in range(0, h):
        for col in range(0, w):
            s = np.random.normal(0, 15, 3)  # 产生随机数,每次产生三个
            b = image[row, col, 0]  # blue
            g = image[row, col, 1]  # green
            r = image[row, col, 2]  # red
            image[row, col, 0] = clamp(b + s[0])
            image[row, col, 1] = clamp(g + s[1])
            image[row, col, 2] = clamp(r + s[2])
    cv.imshow("noise img", image)

高斯模糊

# 高斯模糊抑制高斯噪声
gaussian_noise_demo(src)
# 这里(5, 5)表示高斯矩阵的长与宽都是5,标准差取0时,
# OpenCV会根据高斯矩阵的尺寸自己计算,两个参数设置一个即可。
# 概括地讲,高斯矩阵的尺寸越大,标准差越大,处理过的图像模糊程度越大。
dst = cv.GaussianBlur(src, (5, 5), 0)
cv.imshow("gaussian blur img", dst)

 

代码

# -*- coding: utf-8 -*-
# By:iloveluoluo
# 2019.3.25
import cv2 as cv
import numpy as np

# 高斯模糊:高斯滤波是一种线性平滑低通滤波器,适用于消除高斯噪声,广泛应用于图像处理的减噪过程。
# 滤波高斯就是对整幅图像进行加权平均的过程,每一个像素点的值,都由其本身和邻域内的其他像素值经过加权平均后得到。
# 用一个模板(或称卷积,掩模)扫描图像中的每一个像素,用模板确定的邻域内像素的加权平均灰度值去替代模板中心像素点的值。


def clamp(pv):
    """防止溢出"""
    if pv > 255:
        return 255
    elif pv < 0:
        return 0
    else:
        return pv


def gaussian_noise_demo(image):
    """添加高斯噪声"""
    h, w, c = image.shape
    for row in range(0, h):
        for col in range(0, w):
            s = np.random.normal(0, 15, 3)  # 产生随机数,每次产生三个
            b = image[row, col, 0]  # blue
            g = image[row, col, 1]  # green
            r = image[row, col, 2]  # red
            image[row, col, 0] = clamp(b + s[0])
            image[row, col, 1] = clamp(g + s[1])
            image[row, col, 2] = clamp(r + s[2])
    cv.imshow("noise img", image)


src = cv.imread('E:/MyFile/Picture/date/lenademo.png')  # 读取椒盐噪声图片
cv.imshow("src demo", src)

# tim1 = cv.getCPUTickCount()
# gaussian_noise_demo(src)
# tim2 = cv.getCPUTickCount()
# time = (tim2-tim1)/cv.getTickFrequency()*1000
# print("time: %s ms" % time)

# 高斯模糊抑制高斯噪声
gaussian_noise_demo(src)
# 这里(5, 5)表示高斯矩阵的长与宽都是5,标准差取0时,
# OpenCV会根据高斯矩阵的尺寸自己计算,两个参数设置一个即可。
# 概括地讲,高斯矩阵的尺寸越大,标准差越大,处理过的图像模糊程度越大。
dst = cv.GaussianBlur(src, (5, 5), 0)
cv.imshow("gaussian blur img", dst)

cv.waitKey(0)
cv.destroyAllWindows()

 

  • 2
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值