用python写阶数为n的方形中值滤波器及十字形中值滤波器
时间: 2024-05-01 11:17:19 浏览: 52
daima.rar_中值滤波 十字_方形中值滤波
我可以为您提供相应的代码和算法解释,以下是阶数为n的方形中值滤波器的Python代码:
```
import numpy as np
def square_median_filter(img, n):
# Add padding to the input image to handle border pixels
pad_width = n // 2
padded_img = np.pad(img, pad_width, mode='constant', constant_values=0)
output_img = np.zeros_like(img)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
# Extract the n x n neighborhood around the current pixel
neighborhood = padded_img[i:i+n, j:j+n]
# Compute the median of the neighborhood and assign it to the output
output_img[i, j] = np.median(neighborhood)
return output_img
```
对于十字形中值滤波器,可以使用类似的方法实现,只需要在提取邻域时选择横向和纵向的像素,具体代码如下:
```
import numpy as np
def cross_median_filter(img, n):
# Add padding to the input image to handle border pixels
pad_width = n // 2
padded_img = np.pad(img, pad_width, mode='constant', constant_values=0)
output_img = np.zeros_like(img)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
# Extract the n pixels above and below the current pixel, and to the left and right of it
neighborhood = np.concatenate((padded_img[i-pad_width:i, j], padded_img[i+1:i+pad_width+1, j],
padded_img[i, j-pad_width:j], padded_img[i, j+1:j+pad_width+1]))
# Compute the median of the neighborhood and assign it to the output
output_img[i, j] = np.median(neighborhood)
return output_img
```
以上两个函数均采用了numpy库中的一些函数,需要在代码中先导入numpy库。
阅读全文