我可以使用此代码重现错误消息:
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)
这里的问题是im 是 3 维的,而不是 2 维的。例如,如果您的图像是 RGB 格式,则可能会发生这种情况。
所以im[x,y] 是一个形状为 (3,) 的数组。 new_mat[y, n-1-x] 需要一个 np.uint8 值,但被分配给一个数组。
要修复rotate_by_90_deg,使new_mat 与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()
或者,您可以使用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()