【问题标题】:Python numpy ValueError: setting an array element with a sequencePython numpy ValueError:使用序列设置数组元素
【发布时间】:2015-01-08 22:05:20
【问题描述】:

您好,我试图将图像旋转 90 度,但我不断收到此错误“ValueError: setting an array element with a sequence”,我不确定是什么问题。

当我尝试使用数组运行该函数时,它可以工作,但是当我使用图像尝试它时,我得到了那个错误。

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

【问题讨论】:

  • 谁使用np.rot90
  • 您的图像可能以 im[x,y] 返回包含 1 个元素的数组而不是元素本身的方式存储。 ([0] 而不是 0)。当然,这只是一种可能性,但您可以轻松地检查出来。

标签: python arrays numpy


【解决方案1】:

我可以使用此代码重现错误消息:

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_matim 具有相同的轴数:

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

【讨论】:

    猜你喜欢
    • 2015-12-19
    • 2018-05-09
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    相关资源
    最近更新 更多