numpy 数组深拷贝与浅拷贝

相关问题在这篇博客中已经说得比较清楚:link
补充一个在函数中使用的例子:

import numpy as np
import cv2

def flip_transform(image, label):
    for i in range(image.shape[2]):
        image[:,:,i] = cv2.flip(image[:,:,i], 0)
    label[:] = cv2.flip(label, 0)
    return image, label

def flip_transform1(image, label):
    for i in range(image.shape[2]):
        image[:,:,i] = cv2.flip(image[:,:,i], 0)
    label = cv2.flip(label, 0) # 不再是label[:],这种slice的形式了
    return image, label

image = np.asarray([
    [[1,2],
    [3,4]],

    [[5,6],
    [7,8]]
])
label = np.asarray([[1,2],[3,4]])
'''
flip_transform(image,label)
print(image)
#array([[[5, 6],
        [7, 8]],

       [[1, 2],
        [3, 4]]])
print(label)
#array([[3, 4],
       [1, 2]])

 '''

结果符合自己的想法,即相当与给flip_transform传了实参,label,image 相当于指针,在函数内完成了np数组的改变,但如果调用flip_transform1,结果则会是:

flip_transform1(image,label)
print(image)
#array([[[5, 6],
        [7, 8]],

       [[1, 2],
        [3, 4]]])
print(label)
#array([[1,2],
    [3,4]]) 

label却没有改变,原因可能是因为函数不能改变实参指针的值,只能改变指针指向元素的值。

猜你喜欢

转载自blog.csdn.net/baidu_33939056/article/details/79926399