中值濾波1
import numpy as np
import cv2
from PIL import Image
import scipy.signal as signal
import matplotlib.pyplot as plt
# 創建一個500*500的矩陣
input_images = np.zeros((500, 500))
filename = "E:/pycharm/GraduationDesign/Test/testtwo.png"
# convert將當前圖像轉換為灰度模式,並且返回新的圖像。
# 將圖片在重新定義的矩陣中再顯示,不然可能會只顯示部分。
img = Image.open(filename).resize((500, 500)).convert('L')
plt.subplot(221)
plt.title('原圖', fontproperties=font_set)
plt.imshow(img)
# 圖像的尺寸,按照像素數計算。它的返回值為寬度和高度的二元組(width, height)。
width = img.size[0]
height = img.size[1]
threshold = 130
# 可以改寫代碼使其成為二值化,此代碼可理解為反向二值化
for h in range(height):
for w in range(width):
# getpixel直接獲得(h,w)處的像素直接返回這個點三個通道的像素值
# 返回給定位置的像素值。如果圖像為多通道,則返回一個元組(r,g,b,閾值)。
# 如果改成(w,h)出現的圖像會倒轉
if img.getpixel((w, h)) < threshold:
input_images[h, w] = 1
else:
input_images[h, w] = 0
plt.subplot(222)
plt.title('二值化', fontproperties=font_set)
plt.imshow(input_images)
data = signal.medfilt2d(np.array(img), kernel_size=3) # 二維中值濾波
for h in range(0, height):
for w in range(0, width):
if data[h][w] < 128:
input_images[h, w] = 0
else:
input_images[h, w] = 1
plt.subplot(223)
plt.title('中值濾波去噪(3*3)', fontproperties=font_set)
plt.imshow(input_images)
data = signal.medfilt2d(np.array(img), kernel_size=7) # 二維中值濾波
for h in range(0, height):
for w in range(0, width):
if data[h][w] < 128:
input_images[h, w] = 0
else:
input_images[h, w] = 1
plt.subplot(224)
plt.title('中值濾波去噪(7*7)', fontproperties=font_set)
plt.imshow(input_images)
plt.show()
中值濾波2
from PIL import Image
import numpy as np
def MedianFilter(src, dst, k=3, padding=None):
imarray = np.array(Image.open(src))
height, width = imarray.shape
if not padding:
edge = int((k - 1) / 2)
if height - 1 - edge <= edge or width - 1 - edge <= edge:
print("The parameter k is to large.")
return None
new_arr = np.zeros((height, width), dtype="uint8")
for i in range(height):
for j in range(width):
if i <= edge - 1 or i >= height - 1 - edge or j <= edge - 1 or j >= height - edge - 1:
new_arr[i, j] = imarray[i, j]
else:
# nm:neighbour matrix
nm = imarray[i - edge:i + edge + 1, j - edge:j + edge + 1]
max = np.max(nm)
min = np.min(nm)
if imarray[i, j] == max or imarray[i, j] == min:
new_arr[i, j] = np.median(nm)
else:
new_arr[i, j] = imarray[i, j]
new_im = Image.fromarray(new_arr)
new_im.save(dst)
src = "E:/正課/大二上/計算機網絡/網絡編程/圖像去噪聲/output2/4.jpg"
dst = "E:/正課/大二上/計算機網絡/網絡編程/圖像去噪聲/output2/xxx.jpg"
MedianFilter(src, dst)