0

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
2
  • 2
    Whan to use np.rot90?
    – unutbu
    Commented Jan 8, 2015 at 13:18
  • Your image might be stored in a way that im[x,y] returns an array with 1 element instead of the element itself. ([0] instead of 0). This is only a possibility, of course, but you can easily check this out.
    – leeladam
    Commented Jan 8, 2015 at 13:28

1 Answer 1

2

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

Or, you could use np.rot90:

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()
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.