中值滤波 处理 椒盐噪声

首先对原图像加椒盐噪声,之后经中值滤波

import cv2 as cv
import numpy as np


def noise(img,snr):
    h=img.shape[0]
    w=img.shape[1]
    img1=img.copy()
    sp=h*w
    NP=int(sp*(1-snr))
    for i in range (NP):
        randx=np.random.randint(1,h-1)   # random
        randy=np.random.randint(1,w-1)
        if np.random.random()<=0.5:
            img1[randx,randy]=0
        else:
            img1[randx,randy]=255
    return img1

def mid(img):
    imgInfo = img.shape
    height = imgInfo[0]
    width = imgInfo[1]
    dst = np.empty_like(img, dtype=np.uint8)
    for i in range(height - 2):
        for j in range(width - 2):
            for channel in range(3):
                tmp = img[i:i+3, j:j+3, channel].reshape(1,9)
                dst[i,j, channel] = np.sort(tmp)[0,4]
    return dst


if __name__ == '__main__':
    img = cv.imread("sample.jpg", cv.IMREAD_COLOR)
    cv.imshow("ori", img)
    slat = noise(img, 0.4)
    cv.imshow("median_blur_demo", slat)
    res = mid(img)
    cv.imshow('res',res)
    cv.waitKey(0)

まつりすき
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/white_156/article/details/105640540