import numpy as np

# 自适应中值滤波
def adaptive_median_filter(image, max_window_size=7):
    padded_image = np.pad(image, max_window_size // 2, mode='edge')
    filtered_image = image.copy()
    height, width = image.shape

    for i in range(height):
        for j in range(width):
            window_size = 3
            while True:
                half = window_size // 2
                i1, i2 = i + max_window_size//2 - half, i + max_window_size//2 + half + 1
                j1, j2 = j + max_window_size//2 - half, j + max_window_size//2 + half + 1
                window = padded_image[i1:i2, j1:j2].flatten()
                window = np.sort(window)

                Z_min = window[0]
                Z_max = window[-1]
                Z_med = window[len(window) // 2]
                Z_xy = padded_image[i + max_window_size//2, j + max_window_size//2]

                A1 = Z_med - Z_min
                A2 = Z_med - Z_max

                if A1 > 0 and A2 < 0:  # Level A
                    B1 = Z_xy - Z_min
                    B2 = Z_xy - Z_max
                    if B1 > 0 and B2 < 0:
                        filtered_image[i, j] = Z_xy
                    else:
                        filtered_image[i, j] = Z_med
                    break
                else:
                    window_size += 2
                    if window_size > max_window_size:
                        filtered_image[i, j] = Z_med
                        break

    return filtered_image