对Lena图片生成椒盐噪声,并用OpenCV实现中值滤波/均值滤波,对比可发现中值滤波适合做椒盐噪声消除。
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 14 21:38:06 2017
@author: 18201
"""
#coding=utf-8
import cv2
import numpy as np
def salt(img, n):
for k in range(n):
i = int(np.random.random() * img.shape[1])
j = int(np.random.random() * img.shape[0])
if img.ndim == 2:
img[j,i] = 255
elif img.ndim == 3:
img[j,i,0]= 255
img[j,i,1]= 255
img[j,i,2]= 255
return img
def pepper(img, n):
for k in range(n):
i = int(np.random.random() * img.shape[1])
j = int(np.random.random() * img.shape[0])
if img.ndim == 2:
img[j, i] == 0
elif img.ndim == 3:
img[j,i,0]= 0
img[j,i,1]= 0
img[j,i,2]= 0
return img
img = cv2.imread("lena_.jpg", 0)
saltRe = salt(img, 500)
result = pepper(saltRe, 500)
median3 = cv2.medianBlur(result, 3)
median5 = cv2.medianBlur(result, 5)
cv2.imshow("SaltPepper", result)
cv2.imshow("Median3", median3)
cv2.imshow("Median5", median5)
cv2.waitKey(0)