基于opencv对图片添加高斯模糊和高斯去噪(python)

图片的位置与代码处于一个文件夹下;生成的图片也在同一个文件夹下。

①.添加高斯噪声

import cv2
import numpy as np
import math


# 加高斯噪声
def clamp(pv):
    if pv > 255:
        return 255
    if pv < 0:
        return 0
    else:
        return pv

def gaussian_noise(image):           
    h, w, c = image.shape
    for row in range(h):
        for col in range(w):
            s = np.random.normal(0, 25, 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])
    cv2.imshow("noise_image", image)
    cv2.imwrite('noise.png', image)

src = cv2.imread('tiger.png')
cv2.imshow('input_image', src)

其中src = cv2.imread('tiger.png')中的’tiger.png'更改为需要添加高斯模糊的图片。

②.高斯去噪(高斯模糊)

import cv2
import numpy as np
import math

src = cv2.imread('tiger.png')
#高斯模糊
gaussian_noise(src)
dst = cv2.GaussianBlur(src, (5,5), 0) 
cv2.imshow("Gaussian_Blur", dst)
cv2.imwrite('Gaussian_Blur.png', dst)

cv2.waitKey(0)
cv2.destroyAllWindows()

其中src = cv2.imread('tiger.png')中的tiger.png更改为需要添加高斯模糊的图片。

③.总代码

import cv2
import numpy as np
import math


# 加高斯噪声
def clamp(pv):
    if pv > 255:
        return 255
    if pv < 0:
        return 0
    else:
        return pv

def gaussian_noise(image):           
    h, w, c = image.shape
    for row in range(h):
        for col in range(w):
            s = np.random.normal(0, 25, 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])
    cv2.imshow("noise_image", image)
    cv2.imwrite('noise.png', image)

src = cv2.imread('tiger.png')
cv2.imshow('input_image', src)

#高斯模糊
gaussian_noise(src)
dst = cv2.GaussianBlur(src, (5,5), 0) 
cv2.imshow("Gaussian_Blur", dst)
cv2.imwrite('Gaussian_Blur.png', dst)

cv2.waitKey(0)
cv2.destroyAllWindows()

有问题请留言,会及时回复的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值