出于空间分析的目的,我正在尝试设置一个过滤器,对于给定邻域中的像素,它将在其邻域中给出此像素的百分位数(由结构元素定义)
以下是我迄今为止的最佳镜头:
import numpy as np
import scipy.ndimage as ndimage
import scipy.stats as sp
def get_percentile(values, radius=3):
# Retrieve central pixel and neighbours values
cur_value = values[4]
other_values = np.delete(values, 4)
return sp.percentileofscore(other_values, cur_value)/100
def percentiles(image):
# definition of the neighbourhood (structuring element)
footprint = np.array([[1,1,1],
[1,1,1],
[1,1,1]])
# Using generic_filter to apply sequentially a my own user-defined
# function (`get_percentile`) in the filter
results = ndimage.generic_filter(
image,
get_percentile,
footprint=footprint,
mode='constant',
cval=np.nan)
return results
# Pick dimensions for a dummy example
dims = [12,15]
# Generate dummy example
df = np.random.randn(np.product(dims)).reshape(dims[0], dims[1])
percentiles(df)
有点工作,但是:
我确信代码不是最优的,而且可以运行得更快
我邻居的维度是硬编码的。我想要的是根据此过滤器更好地识别我正在从其邻居应用过滤器(footprint
)的中心像素。