假设下面的数组A
是读取GeoTIFF图像的结果,例如使用没有数据值为masked的rasterio数组B
。
我想在平方邻域上应用棚车平均平滑法。第一个问题是我不确定哪个scipy函数代表棚车平均值?
我认为可能是ndimage.uniform_filter。但是,与scipy.signal相比,ndimage不适用于掩码数组。
from scipy.signal import medfilt
from scipy.ndimage import uniform_filter
import numpy as np
A = np.array([[-9999, -9999, -9999, -9999, -9999, -9999, -9999, -9999],
[-9999, -9999, -9999, -9999, -9999, -9999, -9999, -9999],
[-9999, -9999, -9999, -9999, -9999, -9999, -9999, -9999],
[-9999, -9999, -9999, 0, 300, 400, 200, -9999],
[-9999, -9999, -9999, -9999, 200, 0, 400, -9999],
[-9999, -9999, -9999, 300, 0, 0, -9999, -9999],
[-9999, -9999, -9999, 300, 0, -9999, -9999, -9999],
[-9999, -9999, -9999, -9999, -9999, -9999, -9999, -9999]])
B = np.ma.masked_array(A, mask=(A == -9999))
print(B)
filtered = medfilt(B, 3).astype('int')
result = np.ma.masked_array(filtered, mask=(filtered == -9999))
print(result)
boxcar = ndimage.uniform_filter(B)
print(boxcar)
那么,我该如何应用一个Boxcar平均数来说明无数据值,例如scipy.signal.medfilt?
答案 0 :(得分:0)
这似乎是一个很好的解决方案:
import numpy as np
from scipy.signal import fftconvolve
def boxcar(A, nodata, window_size=3):
mask = (A==nodata)
K = np.ones((window_size, window_size),dtype=int)
out = np.round(fftconvolve(np.where(mask,0,A), K, mode="same")/fftconvolve(~mask,K, mode="same"), 2)
out[mask] = nodata
return np.ma.masked_array(out, mask=(out == nodata))
A = np.array([[100, 100, 100, 100, 100, 100, 100, 100],
[100, 100, 100, 100, 100, 100, 100, 100],
[100, 100, 100, 100, 100, 100, 100, 100],
[100, 100, 100, 100, 1 , 0 , 1 , 100],
[100, 100, 100, 1 , 0 , 1 , 0 , 100],
[100, 100, 100, 0 , 1 , 0 , 1 , 100],
[100, 100, 100, 100, 100, 100, 100, 100]])
print(boxcar(A, 100))
很高兴获得一些反馈,尤其是在改进方面!