From b0d3b92e74cdef187830513c360cc16b7306fec5 Mon Sep 17 00:00:00 2001 From: Stefan van der Walt Date: Sun, 1 Sep 2013 23:44:23 +0200 Subject: [PATCH] Add skip parameter to view_as_windows. --- skimage/util/shape.py | 18 ++++++++++++++---- skimage/util/tests/test_shape.py | 16 ++++++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/skimage/util/shape.py b/skimage/util/shape.py index 0126d2e3..1d606b42 100644 --- a/skimage/util/shape.py +++ b/skimage/util/shape.py @@ -98,7 +98,7 @@ def view_as_blocks(arr_in, block_shape): return arr_out -def view_as_windows(arr_in, window_shape): +def view_as_windows(arr_in, window_shape, step=1): """Rolling window view of the input n-dimensional array. Windows are overlapping views of the input array, with adjacent windows @@ -108,10 +108,12 @@ def view_as_windows(arr_in, window_shape): ---------- arr_in: ndarray The n-dimensional input array. - window_shape: tuple Defines the shape of the elementary n-dimensional orthotope (better know as hyperrectangle [1]_) of the rolling window view. + step : int + Number of elements to skip when moving the window forward (by + default, move forward by one). Returns ------- @@ -212,6 +214,9 @@ def view_as_windows(arr_in, window_shape): if not (len(window_shape) == arr_in.ndim): raise ValueError("'window_shape' is incompatible with 'arr_in.shape'") + if step < 1: + raise ValueError("`step` must be >= 1") + arr_shape = np.array(arr_in.shape) window_shape = np.array(window_shape, dtype=arr_shape.dtype) @@ -224,8 +229,13 @@ def view_as_windows(arr_in, window_shape): # -- build rolling window view arr_in = np.ascontiguousarray(arr_in) - new_shape = tuple(arr_shape - window_shape + 1) + tuple(window_shape) - new_strides = arr_in.strides + arr_in.strides + new_shape = tuple((arr_shape - window_shape) // step + 1) + \ + tuple(window_shape) + + arr_strides = np.array(arr_in.strides) + new_strides = np.concatenate( + (arr_strides * step, arr_strides) + ) arr_out = as_strided(arr_in, shape=new_shape, strides=new_strides) diff --git a/skimage/util/tests/test_shape.py b/skimage/util/tests/test_shape.py index 8c62a191..b6975d0f 100644 --- a/skimage/util/tests/test_shape.py +++ b/skimage/util/tests/test_shape.py @@ -141,5 +141,21 @@ def test_view_as_windows_2D(): [17, 18, 19]]]])) +def test_view_as_windows_With_skip(): + A = np.arange(20).reshape((5, 4)) + B = view_as_windows(A, (2, 2), step=2) + assert_equal(B, [[[[0, 1], + [4, 5]], + [[2, 3], + [6, 7]]], + [[[8, 9], + [12, 13]], + [[10, 11], + [14, 15]]]]) + + C = view_as_windows(A, (2, 2), step=4) + assert_equal(C.shape, (1, 1, 2, 2)) + + if __name__ == '__main__': np.testing.run_module_suite()