Efficiently Reshaping/Reordering Numpy Array to Properly Ordered Tiles (Image)
Question: I would like to be able to somehow reorder a numpy array for efficient
processing of tiles.

what I got:

    
    
    >>> A = np.array([[1,2],[3,4]]).repeat(2,0).repeat(2,1)
    >>> A  # image like array
    array([[[1, 1, 2, 2],
            [1, 1, 2, 2]],
    
           [[3, 3, 4, 4],
            [3, 3, 4, 4]]])
    
    >>> A.reshape(2,2,4)
    array([[[1, 1, 2, 2],
            [1, 1, 2, 2]],
    
           [[3, 3, 4, 4],
            [3, 3, 4, 4]]])
    

what I want: **How to get X:**

    
    
    >>> X
    array([[[1, 1, 1, 1],
            [2, 2, 2, 2]],
    
           [[3, 3, 3, 3],
            [4, 4, 4, 4]]])
    

Is this possible without a slow python loop?

Bonus: Conversion back from X to A

Bago pointed out a similar question I had missed: [Creating a 4D view on 2D
array to divide it into cells of fixed
size](http://stackoverflow.com/questions/9006232/creating-a-4d-view-
on-2d-array-to-divide-it-into-cells-of-fixed-size)

* * *

Why all the trouble? To be able to do something like:

    
    
    >>> X[X.sum(2)>12] -= 1
    >>> X
    array([[[1, 1, 1, 1],
            [2, 2, 2, 2]],
    
           [[3, 3, 3, 3],
            [3, 3, 3, 3]]])
    

**Edit: Solution:**

    
    
    # MIT - License
    
    import numpy as np
    
    def tile_reorder(A, t):
        """reshape and transpose quadratic array for easy access to quadratic tiles of size t"""
        l = A.shape[0] / t
        X = A.reshape((l, t, l, t))
        X = X.transpose([0, 2, 1, 3])
        return X
    
    def tile_reorder_reverse(X):
        l = X.shape[0] * X.shape[2]
        A = X.transpose([0, 2, 1, 3])
        A = A.reshape((l, l))
        return A
    
    if __name__ == "__main__":
        A = np.array([[1,2,3],[3,4,5],[6,7,8]]).repeat(4,0).repeat(4,1)
    
        print "A:\n", A, "\n\n"
    
        print "A_tiled:\n", tile_reorder(A,4), "\n\n"
    
        print "A_tiled_reversed:\n", tile_reorder_reverse(tile_reorder(A,4)), "\n\n"
    
        X = tile_reorder(A,4)
        X[X.sum((2)).sum(2)>63,:,:] += 10
        B = tile_reorder_reverse(X)
    
        print "B_processed:\n", B, "\n\n"
    


Answer: Do you want something like:

    
    
    >>> X = A.reshape(2,2,2,2)
    >>> X = X.transpose([0,2,1,3])
    >>> X = X.reshape((2,2,-1))
    >>> X
    array([[[1, 1, 1, 1],
            [2, 2, 2, 2]],
    
           [[3, 3, 3, 3],
            [4, 4, 4, 4]]])
    >>> B = X.reshape((2,2,2,2))
    >>> B = B.transpose([0,2,1,3])
    >>> B = B.reshape((2,2,-1))
    >>> B
    array([[[1, 1, 2, 2],
            [1, 1, 2, 2]],
    
           [[3, 3, 4, 4],
            [3, 3, 4, 4]]])
    

