Numpy数组:函数也影响原始输入对象

问题描述 投票:1回答:1

我正在使用TensorFlow 2.0中的个人图像增强功能。更具体地说,我写了一个返回随机缩放图像的函数。它的输入是image_batch,一个多维numpy数组,形状:

(no. images, height, width, channel)

在我的具体情况中是:

(31, 300, 300, 3)

这是代码:

def random_zoom(batch, zoom=0.6):
    '''
    Performs random zoom of a batch of images.
    It starts by zero padding the images one by one, then randomly selects
     a subsample of the padded image of the same size of the original.
    The result is a random zoom
    '''

    # Import from TensorFlow 2.0
    from tensorflow.image import resize_with_pad, random_crop

    # save original image height and width
    height = batch.shape[1]
    width = batch.shape[2]

    # Iterate over every image in the batch
    for i in range(len(batch)):
        # zero pad the image, adding 25-percent to each side
        image_distortion = resize_with_pad(batch[i, :,:,:], int(height*(1+zoom)), int(width*(1+zoom)))

        # take a subset of the image randomly
        image_distortion = random_crop(image_distortion, size=[height, width, 3], seed = 1+i*2)

        # put the distorted image back in the batch
        batch[i, :,:,:] = image_distortion.numpy()

    return batch

然后我可以调用该函数:

new_batch = random_zoom(image_batch)

在这一点上,发生了一些奇怪的事情:图像的new_batch就像我预期的那样,我对它感到满意......但现在image_batch,原始的输入对象,已经改变了!我不希望这样,我不明白为什么会这样。

python numpy tensorflow mutable numpy-ndarray
1个回答
2
投票

好吧,这行batch[i, :,:,:] = image_distortion.numpy()修改了作为参数传递的数组。

您的困惑很可能源于对C ++等其他语言的熟悉,其中隐式复制了作为参数传递的对象。

在Python中,您可以通过引用调用传递的内容。除非你想要它们,否则不会制作副本。因此,并不是new_batchimage_batch都被修改了;它们是指向已更改的同一对象的两个名称。

因此,您可能希望在函数开始时执行类似batch = batch.copy()的操作。

© www.soinside.com 2019 - 2024. All rights reserved.