无法将numpy数组值转换为float32

时间:2018-03-19 01:34:11

标签: python numpy

我正在尝试将float64的numpy数组转换为float32。该数组是另外两个数组的连接版本:histn_zero_rows

def someFunction(hist, imgs):
    samples = []
    for img in imgs:
        n_zero = img != 0
        n_zero_cols = n_zero.sum(0) / norm(n_zero.sum(0) + eps)
        n_zero_rows = n_zero.sum(1) / norm(n_zero.sum(1) + eps)

        features = np.concatenate((hist, n_zero_rows), axis=0)      
        samples.append(features)

    return np.float32(samples)

如果我仅将samples数组附加hist,则可行。但是当我尝试添加n_zero_rows时,它会引发异常:ValueError: setting an array element with a sequence。我检查了两个数组的类型,它们都是numpy.ndarrays,这些数组中的两个元素都是float64

编辑:哎呀!它无法真正进行测试。以下是更详细的信息:我确保我的n_zero_rows数组的维度与hist的维度相同。从本质上讲,它只是检查每行的非零像素数量。你可以自己尝试任何图像。这是两个数组的形状和类型:

Shape of img: (128, 128)
Shape of n_zero_rows: (128,)
Shape of hist: (120,)
type of n_zero_rows: <type 'numpy.ndarray'>
type of hist: <type 'numpy.ndarray'>

并且只是为了确保,这里是循环中第一个n_zero_rows的{​​{1}}(NORMALIZED):

img

我不明白为什么它适用于[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.03518132 0.04073627 0.02777473 0.03703297 0.02777473 0.05925276 0.07406595 0.09258243 0.11850551 0.14998354 0.15739014 0.15553849 0.15924178 0.15553849 0.15553849 0.15739014 0.15924178 0.15924178 0.16109343 0.16109343 0.16109343 0.15739014 0.15924178 0.16109343 0.15924178 0.16109343 0.16109343 0.16109343 0.16109343 0.15924178 0.16109343 0.16109343 0.16664838 0.17035168 0.17035168 0.17220333 0.14628024 0.14257695 0.1444286 0.12591211 0.10369233 0.09813738 0.10184068 0.09813738 0.09998903 0.09628573 0.09998903 0.09443408 0.09813738 0.09998903 0.09258243 0.09813738 0.09998903 0.09998903 0.09813738 0.09628573 0.08147254 0.08147254 0.07776924 0.07776924 0.05369781 0.04814287 0.02962638 0.02962638 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ] 而不是hist

1 个答案:

答案 0 :(得分:0)

我们问了一个例子,我们可以实际运行和测试。没有它我们只能猜测。这是产生此错误的最小示例。还有其他事情可以做到,但我怀疑这是最可能的情况:

In [770]: np.float32([[1,2],[3,4]])
Out[770]: 
array([[1., 2.],
       [3., 4.]], dtype=float32)
In [771]: np.float32([[1],[3,4]])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-771-0b5ad69cbd8c> in <module>()
----> 1 np.float32([[1],[3,4]])

ValueError: setting an array element with a sequence.