scipy.ndimage.filters.generic_filter
是否可以在filter 函数中获取“当前元素” ?
例如,如果A[0]
始终包含当前元素(似乎并非如此),则类似以下内容可能会找到局部最大值
def local_max_f(A) :
return A[0] == A.max()
img = np.random.rand(100).reshape(10,10)
ndimage.generic_filter( img, local_max_f, size=3 )
当前元素应该是size
(或A[1]
在您的示例中)中心的元素,但这不能依赖于输入数组的边缘,并且取决于mode
处理数组边界的方法。
相反,文档提供了一个简洁的示例(适用于您在下面的情况),用于使用类来确定过滤器中的当前位置,以维持迭代之间的某些状态。这总是首先遍历最后一个维度;您所要做的就是用result
您的过滤器功能实际需要做的任何事情替换该行,在您的情况下,这将类似于result = self._array[self.coordinates] == buffer.max()
.
a = arange(12).reshape(3,4)
class fnc_class:
def __init__(self, _array):
# store the shape:
self.shape = _array.shape
self._array = _array
# initialize the coordinates:
self.coordinates = [0] * len(self.shape)
def filter(self, buffer):
result = self._array[tuple(self.coordinates)] == buffer.max()
print self.coordinates
# calculate the next coordinates:
axes = range(len(self.shape))
axes.reverse()
for jj in axes:
if self.coordinates[jj] < self.shape[jj] - 1:
self.coordinates[jj] += 1
break
else:
self.coordinates[jj] = 0
return result
fnc = fnc_class(a)
generic_filter(a, fnc.filter, footprint = [[1, 0], [0, 1]])