Python 为什么这个函数会影响一个甚至没有传递给它的变量?
问题从线路开始Python 为什么这个函数会影响一个甚至没有传递给它的变量?,python,Python,问题从线路开始 def detectFaceOfImage(self,cascade_path, path): print "Detecting facing from image in",path,"..." print img = cv.imread(path) face_cascade = cv.CascadeClassifier(cascade_path) gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
def detectFaceOfImage(self,cascade_path, path):
print "Detecting facing from image in",path,"..."
print
img = cv.imread(path)
face_cascade = cv.CascadeClassifier(cascade_path)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.5, 1)
for (x, y, w, h) in faces:
# cv.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
self.crop_img.append(img[y:y + h, x:x + w])
self.gray_img.append(gray[y:y + h, x:x + w])
print "Finished detecting faces, stored in crop_img and gray_img..."
print
self.crop_img, self.gray_img = self.checkAndFixSize(self.crop_img, self.gray_img)
temp = self.gray_img
# self.exportImages(crop_img, gray_img)
temp = self.normalizeImages(temp)
self.exportImages(self.crop_img, self.gray_img)
def normalizeImages(self, gray_img_here):
print "Normalizing the gray images..."
print
gray_img_numpy = np.array(gray_img_here)
for i in range(len(gray_img_here)):
print
# print "mean of the {}th image", np.mean(gray_img_numpy[i])
# print "std dev. of the {}th image", np.std(gray_img_numpy[i])
# print
gray_img_here[i] = (gray_img_here[i] - np.mean(gray_img_numpy[i]))
return gray_img_here
def exportImages(self, crop_img, gray_img):
print "Writing cropped images into directories..."
print
for i in range(0, len(crop_img), 1):
filename = "cropped_images/img{}.jpg".format(i)
filenamegray = "cropped_gray_images/grayimg{}.jpg".format(i)
cv.imwrite(filename, crop_img[i])
cv.imwrite(filenamegray, gray_img[i])
print("Done!")
在detectFaceOfImage函数中。我将temp传递给normalizeImages,但不知何故,即使变量gray_img也会受到此函数的影响。
当我导出gray_img时,它会显示标准化的临时图像,即使gray_img的内存没有任何改变。请帮帮我。我不知道为什么会发生这种情况。如果数据是一个列表或任何其他对象,则需要一个深度副本 看看这个:
temp = self.gray_img
如果你有
>>> def mutate(data):
... data[0]=101
...
>>> L=[1,2,3]
>>> temp=L
>>> mutate(temp)
>>> temp
[101, 2, 3]
>>> L
[101, 2, 3]
如果您的类型不是列表,只需将指示的类型设置为深度复制。什么是灰色?这里有很多代码,我不知道在哪里初始化itetmp和self.gray\u img是同一个对象。将对象分配给新变量不会复制它。@doctorlove gray images是表示图像的二维数组列表。它是全局初始化的,我在detectFaceOfImage@khelwood是的,我知道它们指向相同的内存,但我认为函数参数只在函数范围内本地存储。在我的所有其他函数中,当我传递其他变量时,原始变量不会受到影响。地址存储在本地,但引用外部对象。如果传入与对象不同的整数。试试身份证功能谢谢!我不知道列表的工作方式与其他数据类型不同,内存甚至可以在函数范围内更改。列表与其他对象没有什么不同。赋值=倾向于引用原始对象。你必须更努力地得到一份新的。id函数会告诉你他们住在哪里。如果地址是dsame,则它们引用相同的地址thing@SharanNarasimhan它不仅仅是列表,它是所有可变类型,其中最常见的是:list、dict、set、bytearrayBut通常在将变量作为函数参数传递时,我的印象是函数只在其作用域内创建本地副本,因此,您所做的任何更改都不会影响最初传递的变量,这是错误的吗?对不起,我的无知问题请原谅:@SharanNarasimhan该函数不创建对象的本地副本。变量是本地副本,但它引用的对象与函数外部的对象相同。改变一个变量不同于改变一个变量所持有的对象。
>>> L=[1,2,3]
>>> temp=list(L) #<--- deep copy here
>>> mutate(temp)
>>> temp
[101, 2, 3]
>>> L
[1, 2, 3]