Python随机生成椒盐噪声

在看opencv网课的时候,老师讲了中值滤波函数---

cv.medianBlur()

并演示了一下滤波前后的效果。但是我用的素材包里没有含有椒盐噪声的图像,所以就自己写了个代码生成了一张,代码如下:

def piper_demo(image):
    copy_image = image.copy()
    numb_of_noise = 200
    h, w = copy_image.shape[:2]
    for i in range(numb_of_noise):
        copy_image[np.random.randint(0, h + 1), np.random.randint(0, w + 1)] = np.random.randint(2) * 255
    cv.imshow('Piper', copy_image)
    return copy_image

下面放出来滤波代码和效果:

import cv2 as cv
import numpy as np


def piper_demo(image):
    copy_image = image.copy()
    numb_of_noise = 200  # number of piper noise point(SNR)
    w, h = copy_image.shape[:2]
    for i in range(numb_of_noise):
        copy_image[np.random.randint(w), np.random.randint(h)] = np.random.randint(2) * 255
    cv.imshow('piper_image', copy_image)
    return copy_image


def blur_demo(image):
    mean_blur_image = cv.blur(image, (5, 5))
    cv.imshow('mean_image', mean_blur_image)

    median_blur_image = cv.medianBlur(image, 5)
    cv.imshow('media_image', median_blur_image)


src = cv.imread('D:/sample/lena.jpg')
cv.imshow('original_image', src)

piper_image = piper_demo(src)
blur_demo(piper_image)

cv.waitKey()
Python随机生成椒盐噪声_第1张图片 原始Lena姐图像 Python随机生成椒盐噪声_第2张图片 加椒盐噪声

 

Python随机生成椒盐噪声_第3张图片 均值滤波结果 Python随机生成椒盐噪声_第4张图片 中值滤波结果

 

你可能感兴趣的:(opencvLearinig)