List of 2D Arrays with numpy

75 views Asked by At

I have a 2D ndarry / array with shape (4096,2048). I am trying to make a list of different portions of this array that are all 40x40.

I've tried append and concatenate, but with no luck. Here's what I have:

#img = the 4096x2048 array. 
# I want to store 100 different 40x40 slices in cropped. The first #slice should start at 186, 290

cropped = img[186:226, 290:330]
for i in range(0,100):
    cropped_image = img[a: a+40, b:b+40]
    cropped.append(cropped,cropped_image)
    a += 1
    b += 1
return cropped
1

There are 1 answers

0
Cory Kramer On

You could use a list comprehension to make a list of these sub-arrays

import itertools
cropped = [img[i:i+40, j:j+40] for i,j in itertools.product(range(0, 4096, 40), range(0, 2048, 40)]

This will give you a list of

[img[0:40, 0:40], img[40:80, 0:40], ...
 img[0:40, 40:80], img[40:80, 40:80], ...
 ...]