0

I've done research and looked over several questions on SO to figure out the proper set-up of strides and shape, but it's been giving me problems.

I have an image array of shape (250, 250, 4) (example) and need to use as_strided to create a sliding window of size (50, 50) across all channels.

Assuming:

x = np.random.random((250, 250, 4)) * 255
image = x.astype(np.uint8)
strided = np.lib.stride_tricks.as_strided(image, shape=(?, ?, ?, ?, ?), strides=(?, ?, ?, ?, ?))

Meaning strided[0, 0, 0] would return the R channel of shape (50,50) equivalent to image[0:50, 0:50, 0], and strided[1, 1, 2] would return the B channel equivalent to image[50:100, 50:100, 2]

I'm needing to use as_strided because I am given a memory view of a massive image (multiple GB in size), the above is just an example to illustrate the problem.

Jack Avante
  • 1,405
  • 1
  • 15
  • 32
  • The `sliding window` function was added as the safer and easier cover for `as_strided`. Would it work for you? – hpaulj Apr 28 '22 at 16:58
  • @hpaulj Thank you for the suggestion, I have already actually tried using that, and found that I am unable. The object I'm provided was an odd implementation of `__array__` which prevents me from using it. I'm unsure if `sliding_window_view` is implemented using `as_strided`, so I wanted to at least give it a try. – Jack Avante Apr 28 '22 at 18:18

1 Answers1

0

A couple of possibilities with sliding_window:

In [9]: arr = np.ones((250,250,4),int)
In [10]: x = np.lib.stride_tricks.sliding_window_view(arr,(50,50),(0,1))
In [11]: x.shape
Out[11]: (201, 201, 4, 50, 50)
In [12]: x = np.lib.stride_tricks.sliding_window_view(arr,(50,50,4))
In [13]: x.shape
Out[13]: (201, 201, 1, 50, 50, 4)

In the first case, strides is: (8000, 32, 8, 8000, 32)

In the second, (8000, 32, 8, 8000, 32, 8)

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Unfortunately in my case I am unable to use `sliding_window_view` to figure out the strides and shape, since my actual image is massive and also a custom object that doesn't accept the usage of `sliding_window_view`. Also, I believe that the `dtype` of `arr` in your answer is `np.int32` which would not work with my example in the question that uses `np.uint8`, so the strides would be different here as well. – Jack Avante Apr 28 '22 at 18:45