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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

In case I want to combine the images later, is there a smart way of doing so?
What do you mean by 'combine'?
to overlay each array to the "right" position it was taken from. Does it make sense?
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, 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.