Python 使用'复制numpy数组=';操作人员为什么它能工作?

Python 使用'复制numpy数组=';操作人员为什么它能工作?,python,numpy,Python,Numpy,根据答案,B=A其中A是一个numpy数组,B应该指向同一个对象A import cv2 import numpy as np img = cv2.imread('rose.jpeg') print("img.shape: ", np.shape(img)) img2 = img img = cv2.resize(img, (250,100)) print("img.shape: ", img.shape) print("img2.shape:", img2.shape) 输出: img.

根据答案,
B=A
其中
A
是一个numpy数组,
B
应该指向同一个对象
A

import cv2
import numpy as np

img = cv2.imread('rose.jpeg')
print("img.shape: ", np.shape(img))

img2 = img
img = cv2.resize(img, (250,100))
print("img.shape: ", img.shape)
print("img2.shape:", img2.shape)
输出:

img.shape:  (331, 500, 3)
img.shape:  (100, 250, 3)
img2.shape: (331, 500, 3)
这似乎是一个非常基本的问题,但我一直在挠头。有人能解释一下它背后发生了什么吗?

问题是,您在这里不使用numpy,而是使用opencv,而numpy array.resize()已就位opencv img.resize()未就位

那么你打电话给

    img = cv2.resize(img, (250,100))
创建具有给定大小的新对象(图像)。因此,这里img变量将指向调用之前的另一个对象

    img2 = img
为原始对象添加新名称。这里img2和img指的是完全相同的对象/内存块

    img = cv2.resize(img, (250,100))
cv2.resize(img,(250100))
创建一个新对象,名称
img
现在指的是新对象/内存块

    print("img.shape: ", img.shape)
获取新对象的大小和

    print("img2.shape:", img2.shape)
原始对象的大小(如img2)仍然指原始对象


顺便说一句,在numpy中调用
a=a.resize(…)
将非常糟糕,因为
a
将被
None
(返回值
resize
)而不是调整大小的数组。在这里,您只需执行
a.resize(…)

img=…
之后,名称
img
引用一个新对象,而
img2
仍然是前一个对象。看看