0

I have the an image represented in nd-array. Let's assume that the shape of it is (256, 256, 3).

I wish to slice the image to sub arrays each of size (128, 128, 3) with a stride of 64.

I did the following to get the desired indices:

for x1, x2 in (zip(range(0, 257, 64), range(128, 257, 64))):
    for y1, y2 in (zip(range(0, 257, 64), range(128, 257, 64))):
        print("rows:",x1,x2,", columns:",y1,y2)

I get the following indices to slice:

rows: 0 128 , columns: 0 128
rows: 0 128 , columns: 64 192
rows: 0 128 , columns: 128 256
rows: 64 192 , columns: 0 128
rows: 64 192 , columns: 64 192
rows: 64 192 , columns: 128 256
rows: 128 256 , columns: 0 128
rows: 128 256 , columns: 64 192
rows: 128 256 , columns: 128 256

Now I can slice each sub array and stack it, moreover, I will want to stack the slices again after some operations on each sub-array and averaging the values.

I was wondering if there is a smarter way of doing it to be able to use it for multiple strides/image sizes.

David
  • 8,113
  • 2
  • 17
  • 36

1 Answers1

2

you want skimage.util.view_as_windows

arr = np.random.rand(256, 256, 3)
out = skimage.util.view_as_windows(arr, window_shape = (128, 128, 3), step = 64).squeeze()
print(out.shape)
Out[]: (3, 3, 128, 128, 3)

That's a (3, 3) array of your (128, 128, 3) image patches.

You can also use my (admittedly outdated since view_as_windows was implemented for nD) custom recipe here which might be helpful if you only have numpy

Daniel F
  • 13,620
  • 2
  • 29
  • 55
  • In case I want to combine the images later, is there a smart way of doing so? – David Nov 05 '20 at 12:59
  • What do you mean by 'combine'? – Daniel F Nov 05 '20 at 13:00
  • to overlay each array to the "right" position it was taken from. Does it make sense? – David Nov 05 '20 at 13:02
  • Not really. The data is still in the "right" position as it is, this is just view on the original data, not a copy. But writing *into* the view is a [one-way ticket to a race condition](https://stackoverflow.com/a/45812234/4427777), and both my recipe and `view_as_windows` try to prevent that. In any case, once you know what you want to do with it you can post another question. – Daniel F Nov 05 '20 at 13:05