Skip to content Skip to sidebar Skip to footer

Reshaping A Numpy Array Into Lexicographical List Of Cubes Of Shape (n, N, N)

In order to understand what I'm trying to achieve let's imagine an ndarray a with shape (8,8,8) from which I lexicographically take blocks of shape (4,4,4). So while iterating thro

Solution 1:

It is a bit unclear what you want as output. Are you looking for this:

from skimage.util.shape importview_as_windowsb= view_as_windows(a,(f,f,f),f).reshape(-1,f,f,f).transpose(1,2,3,0).reshape(f,f,-1)

suggested by @Paul with similar result (I prefer this answer in fact):

N = 8b = a.reshape(2,N//2,2,N//2,N).transpose(1,3,0,2,4).reshape(N//2,N//2,N*4)

output:

print(np.array_equal(b[:, :, 4:8],a[0:4, 0:4, 4:8]))
#True
print(np.array_equal(b[:, :, 8:12],a[0:4, 4:8, 0:4]))
#True
print(np.array_equal(b[:, :, 12:16],a[0:4, 4:8, 4:8]))
#True

Solution 2:

def flatten_by(arr, atomic_size):
    a, b, c = arr.shape
    x, y, z = atomic_size
    
    r = arr.reshape([a//x, x, b//y, y, c//z, z])
    r = r.transpose([0, 2, 4, 1, 3, 5])
    r = r.reshape([-1, x, y, z])
    
    return r
flatten_by(arr, [4,4,4]).shape

>>>   (8, 4, 4, 4)

EDIT:

the function applies C-style flattening to the array, as shown below

NOTE: this method and @Ehsan's method both produce "copies" NOT "views", im looking into it and would update the answer when if i find a solution

flattened = flatten_by(arr, [4,4,4])

required = np.array([
    arr[0:4, 0:4, 0:4],
    arr[0:4, 0:4, 4:8],  
    arr[0:4, 4:8, 0:4],  
    arr[0:4, 4:8, 4:8],  
    arr[4:8, 0:4, 0:4],  
    arr[4:8, 0:4, 4:8],  
    arr[4:8, 4:8, 0:4],  
    arr[4:8, 4:8, 4:8],  
])
np.array_equal(required, flattened)

>>>True

Post a Comment for "Reshaping A Numpy Array Into Lexicographical List Of Cubes Of Shape (n, N, N)"