Python numpy ValueError: setting an array element with a sequence
Question: hi im trying to rotate an image 90 degree's but i keeep getting this error
"ValueError: setting an array element with a sequence" and im not sure whats
the problem.

when i try and run the function with an array it works, but when i try it with
an image i get that error.

    
    
    def rotate_by_90_deg(im):
        new_mat=np.zeros((im.shape[1],im.shape[0]),  dtype=np.uint8)
        n = im.shape[0]
        for x in  range(im.shape[0]):
            for y in range(im.shape[1]):
                new_mat[y,n-1-x]=im[x,y]
        return new_mat
        pass
    


Answer: I can reproduce the error message with this code:

    
    
    import numpy as np
    def rotate_by_90_deg(im):
        new_mat=np.zeros((im.shape[1],im.shape[0]),  dtype=np.uint8)
        n = im.shape[0]
        for x in  range(im.shape[0]):
            for y in range(im.shape[1]):
                new_mat[y,n-1-x]=im[x,y]
        return new_mat
    
    im = np.arange(27).reshape(3,3,3)
    rotate_by_90_deg(im)
    

The problem here is that `im` is 3-dimensional, not 2-dimensional. That might
happen if your image is in RGB format, for example. So `im[x,y]` is an array
of shape (3,). `new_mat[y, n-1-x]` expects a `np.uint8` value, but instead is
getting assigned to an array.

* * *

To fix `rotate_by_90_deg`, make `new_mat` have the same number of axes as
`im`:

    
    
    import numpy as np
    import matplotlib.pyplot as plt
    np.random.seed(1)
    
    def rotate_by_90_deg(im):
        H, W, V = im.shape[0], im.shape[1], im.shape[2:]
        new_mat = np.empty((W, H)+V, dtype=im.dtype)
        n = im.shape[0]
        for x in  range(im.shape[0]):
            for y in range(im.shape[1]):
                new_mat[y,n-1-x]=im[x,y]
        return new_mat
    
    im = np.random.random((3,3,3))
    arr = rotate_by_90_deg(im)
    fig, ax = plt.subplots(ncols=2)
    ax[0].imshow(10*im, interpolation='nearest')
    ax[0].set_title('orig')
    ax[1].imshow(10*arr, interpolation='nearest')
    ax[1].set_title('rot90')
    plt.show()
    

## ![enter image description here](http://i.stack.imgur.com/fYy8I.png)

Or, you could use
[`np.rot90`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.rot90.html):

    
    
    import numpy as np
    import matplotlib.pyplot as plt
    np.random.seed(1)
    im = np.random.random((3,3,3))
    arr = np.rot90(im, 3)
    fig, ax = plt.subplots(ncols=2)
    ax[0].imshow(10*im, interpolation='nearest')
    ax[0].set_title('orig')
    ax[1].imshow(10*arr, interpolation='nearest')
    ax[1].set_title('rot90')
    plt.show()
    

