【问题标题】:one code segment error that might be related to python 2.7 vs python 3.x一个可能与 python 2.7 vs python 3.x 相关的代码段错误
【发布时间】:2023-03-26 10:04:01
【问题描述】:

我正在尝试重用以下代码段。特定的代码行gt_bg = gt_bg.reshape(*gt_bg.shape, 1) 给了我诸如

之类的错误消息
gt_bg = gt_bg.reshape(*gt_bg.shape, 1)
SyntaxError: only named arguments may follow *expression

我正在使用Python 2.7,是这个问题吗?如果是这样,如何修改它以使其适合Python2.7?谢谢。

for image_file in image_paths[batch_i:batch_i+batch_size]:
            gt_image_file = label_paths[os.path.basename(image_file)]

            image = scipy.misc.imresize(scipy.misc.imread(image_file), image_shape)
            gt_image = scipy.misc.imresize(scipy.misc.imread(gt_image_file), image_shape)

            gt_bg = np.all(gt_image == background_color, axis=2)
            gt_bg = gt_bg.reshape(*gt_bg.shape, 1)
            gt_image = np.concatenate((gt_bg, np.invert(gt_bg)), axis=2)

            images.append(image)
            gt_images.append(gt_image)

【问题讨论】:

    标签: python-2.7 python-3.x numpy scipy


    【解决方案1】:

    这与 Python 2 / Python 3 的区别并没有真正的关系,这是一条红鲱鱼。

    numpy 数组的 reshape 方法期望直接接收新形状,作为一个元组,而不是解压缩成维度。所以,而不是这个:

    gt_bg = gt_bg.reshape(*gt_bg.shape, 1)
    

    期待这个:

    gt_bg = gt_bg.reshape(gt_bg.shape + (1,))
    

    或者,如果你想酷,你可以直接设置形状:

    gt_bg.shape += (1,)
    

    或者,如果你想变得古怪,你可以在切片中使用Ellipsis:

    gt_bg = gt_bg[...,None]
    

    【讨论】:

    • 感谢您的回复。据称原始代码段在 python3.x 上运行良好。我在 Python 2.7 下运行它给了我错误的信息。这就是为什么我怀疑它是python版本问题。此外, gt_bg.shape + (1,) 是什么意思?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 2018-01-19
    • 2014-02-11
    • 2013-04-11
    相关资源
    最近更新 更多