【问题标题】:TypeError: 'generator' object cannot be interpreted as an integerTypeError:“生成器”对象不能解释为整数
【发布时间】:2021-10-14 22:15:30
【问题描述】:

回溯错误:

Traceback (most recent call last):
  File "C:\trial2\trial.py", line 56, in <module>
    image_stack(image)
  File "C:\trial2\trial.py", line 44, in image_stack
    reshaped = transposed_axes.reshape(new_arr_shape)
TypeError: 'generator' object cannot be interpreted as an integer

我在代码中的问题是我无法用新的数组形状重塑转置的数组。该代码采用 cv2 读取的图像路径,然后将其转换为数组。使用数组的长度计算转置轴的值。然后转置轴值用于转置数组。我将numpy.prod() 用于if 语句生成的轴上的数组值的乘积。我想用new_arr_shape 的值重塑转置数组,但我一直收到错误消息,说'generator' object cannot be interpreted as an integer

import numpy as np 

def image_stack(image):
    imgs = np.array(cv2.imread(image).shape)
    print(type(imgs))
    n = len(imgs)
    img = np.ones(imgs)
    val_1 = list(range(1, n - 1, 2))
    val_2 = list(range(0, n - 1, 2))
    print(img)
    if n % 2 == 0:
        y_ax = val_1
        x_ax = val_2
        axes = (y_ax, x_ax, [n-1])
    else:
        y_ax = val_2
        x_ax = val_1
        axes = (y_ax, x_ax, [n - 1])
    print(type(axes))
    '''The axes need to be in form of a tuple in order to be
    transposed'''
    if type(axes) == tuple:
        transposed_axes = np.transpose(img, axes=np.concatenate(axes))
        print(transposed_axes)
        new_arr_shape = [np.prod(img[x] for x in axes)]
        print(type(new_arr_shape))
        print(new_arr_shape)
        reshaped = transposed_axes.reshape(new_arr_shape)
        #print(type(reshaped))
        #print(reshaped)
image = 'C:\\trial_images\\9.jpg'
image_stack(image)

【问题讨论】:

    标签: arrays numpy reshape transpose cv2


    【解决方案1】:

    'generator' 对象不能被解释为整数

    这是因为np.prod(img[x] for x in axes) 返回一个生成器,而函数reshape 需要一个整数列表。 要将生成器转换为列表,请使用list 函数。

    list(np.prod(img[x] for x in axes))

    reshape 函数需要一个整数列表或元组。此外,大小(维度的乘积)应与其他数组的大小相匹配。

    例如:transposed_axes.reshape([1446,2842,3])transposed_axes.reshape([1446,1421,6]) 将起作用,因为 transposed_axes 的维度是 (1446,2842,3)

    【讨论】:

    • 我按照你说的把它改成了一个列表,但是我有一个新的错误reshaped = transposed_axes.reshape(list(new_arr_shape)) TypeError: 'numpy.float64' object cannot be interpreted as an integer
    猜你喜欢
    • 2017-08-01
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2015-03-18
    • 2016-01-26
    相关资源
    最近更新 更多