【问题标题】:Numpy array: Function affects original input object as wellNumpy数组:函数也会影响原始输入对象
【发布时间】:2019-09-10 20:47:36
【问题描述】:

我正在 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】:

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

    您的困惑可能源于对另一种语言的熟悉,例如 C++,其中作为参数传递的对象被隐式复制。

    在 Python 中,发生的事情就是您可能称之为通过引用传递的事情。除非您希望复制它们,否则不会制作副本。因此,并不是new_batchimage_batch都被修改了;它们是两个名称,指向已更改的相同对象。

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

    【讨论】:

    • 谢谢,现在可以了。但是,我在 numpy 文档中找到了np.copy(batch)
    • @Leevo 对于大多数意图和目的,copy 方法与 np.copy 相同。
    猜你喜欢
    • 2020-08-09
    • 1970-01-01
    • 2015-01-23
    • 2021-09-28
    • 2013-03-29
    • 2023-01-02
    • 2021-04-01
    • 1970-01-01
    • 2012-11-24
    相关资源
    最近更新 更多