You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
79 lines
2.7 KiB
79 lines
2.7 KiB
2 years ago
|
import random
|
||
|
|
||
|
import cv2
|
||
|
import numpy as np
|
||
|
|
||
|
|
||
|
class noiseCanceller:
|
||
|
def __init__(self, imgPath):
|
||
|
self.path = imgPath
|
||
|
|
||
|
def noiseDescriber(self):
|
||
|
image = cv2.imread(self.path, cv2.IMREAD_GRAYSCALE)
|
||
|
output = np.zeros(image.shape, np.uint8)
|
||
|
prob = 0.2
|
||
|
thres = 1 - prob
|
||
|
# 遍历图像,获取叠加噪声后的图像
|
||
|
for i in range(image.shape[0]):
|
||
|
for j in range(image.shape[1]):
|
||
|
rdn = random.random()
|
||
|
if rdn < prob:
|
||
|
# 添加胡椒噪声
|
||
|
output[i][j] = 0
|
||
|
elif rdn > thres:
|
||
|
# 添加食盐噪声
|
||
|
output[i][j] = 255
|
||
|
else:
|
||
|
# 不添加噪声
|
||
|
output[i][j] = image[i][j]
|
||
|
cv2.imwrite("saved Img/out.bmp", output)
|
||
|
|
||
|
def meanFilter(self):
|
||
|
image = cv2.imread(self.path, cv2.IMREAD_GRAYSCALE)
|
||
|
output = np.zeros(image.shape, np.uint8)
|
||
|
for i in range(image.shape[0]):
|
||
|
for j in range(image.shape[1]):
|
||
|
ij = 1
|
||
|
for m in range(-1, 2):
|
||
|
if 0 <= j + m < image.shape[1]:
|
||
|
ij *= image[i][j + m]
|
||
|
output[i][j] = ij ** (1 / 3)
|
||
|
cv2.imwrite("saved Img/mean filter.bmp", output)
|
||
|
|
||
|
def sortFilter(self):
|
||
|
def get_max(array):
|
||
|
length = len(array)
|
||
|
for i in range(length):
|
||
|
for j in range(i + 1, length):
|
||
|
if array[j] > array[i]:
|
||
|
temp = array[j]
|
||
|
array[j] = array[i]
|
||
|
array[i] = temp
|
||
|
return array[0]
|
||
|
|
||
|
image = cv2.imread(self.path, cv2.IMREAD_GRAYSCALE)
|
||
|
output = np.zeros(image.shape, np.uint8)
|
||
|
array = []
|
||
|
for i in range(image.shape[0]):
|
||
|
for j in range(image.shape[1]):
|
||
|
array.clear()
|
||
|
for m in range(-1, 2):
|
||
|
for n in range(-1, 2):
|
||
|
if 0 <= i + m < image.shape[0] and 0 <= j + n < image.shape[1]:
|
||
|
array.append(image[i + m][j + n])
|
||
|
|
||
|
output[i][j] = get_max(array)
|
||
|
cv2.imwrite("saved Img/sort filter.bmp", output)
|
||
|
|
||
|
def selectiveFilter(self):
|
||
|
image = cv2.imread(self.path, cv2.IMREAD_GRAYSCALE)
|
||
|
output = np.zeros(image.shape, np.uint8)
|
||
|
minimum = 200
|
||
|
for i in range(image.shape[0]):
|
||
|
for j in range(image.shape[1]):
|
||
|
if minimum < image[i][j]:
|
||
|
output[i][j] = image[i][j]
|
||
|
else:
|
||
|
output[i][j] = 0
|
||
|
cv2.imwrite("saved Img/selective filter.bmp", output)
|