我已經找到兩個可以計算平均值,最大值,最小值,方差等的移動窗口的解決方案。現在,我想添加一個計數的唯一值功能按座標軸。按軸來說,我的意思是計算所有二維數組單通道。在Python中添加一個獨特的值過濾器以跨越移動窗口
len(numpy.unique(array))可以做到這一點,但需要很多迭代來計算所有數組。我可能使用的圖像大小爲2000 x 2000,因此迭代不是一個好的選擇。這關乎性能和記憶的有效性。
下面是大踏步移動窗口的兩個解決方案:
首先直接從埃裏克Rigtorp的在http://gozhnikov.github.io/2015/09/30/NumpyTipsAndTricks2.html取自http://www.mail-archive.com/[email protected]/msg29450.html
import numpy as np
def rolling_window_lastaxis(a, window):
if window < 1:
raise ValueError, "`window` must be at least 1."
if window > a.shape[-1]:
raise ValueError, "`window` is too long."
shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
strides = a.strides + (a.strides[-1],)
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
def rolling_window(a, window):
if not hasattr(window, '__iter__'):
return rolling_window_lastaxis(a, window)
for i, win in enumerate(window):
if win > 1:
a = a.swapaxes(i, -1)
a = rolling_window_lastaxis(a, win)
a = a.swapaxes(-2, i)
return a
filtsize = (3, 3)
a = np.zeros((10,10), dtype=np.float)
a[5:7,5] = 1
b = rolling_window(a, filtsize)
blurred = b.mean(axis=-1).mean(axis=-1)
二從亞歷克斯Rogozhnikov。
def compute_window_mean_and_var_strided(image, window_w, window_h):
w, h = image.shape
strided_image = np.lib.stride_tricks.as_strided(image,
shape=[w - window_w + 1, h - window_h + 1, window_w, window_h],
strides=image.strides + image.strides)
# important: trying to reshape image will create complete 4-dimensional compy
means = strided_image.mean(axis=(2,3))
mean_squares = (strided_image ** 2).mean(axis=(2, 3))
maximums = strided_image.max(axis=(2,3))
variations = mean_squares - means ** 2
return means, maximums, variations
image = np.random.random([500, 500])
compute_window_mean_and_var_strided(image, 20, 20)
有沒有辦法在一個或兩個解決方案中添加/實現唯一值函數計數?
說明:基本上,我需要一個二維數組的唯一值過濾器,就像numpy.ndarray.mean。你
亞歷
那麼,你正試圖在一個座標軸上的滑動窗口中計算「唯一值函數的數量」? – Divakar
您的移動窗口尺寸和偏移量如何比較?顯然,偏移越小,潛在的節省就越高。實際上,在這些代碼片段中實現手段等的方式對我來說遠非最佳。 –
@Divakar我試圖添加一個獨特的數值,就像Alex Rogozhnikov的means = strided_image.mean(axis =(2,3))或maximums = strided_image.max(axis =(2,3))例但更像unique = strided_image.unique(axis =(2,3))。 –