为什么此函数影响一个甚至没有传递给它的变量?

时间:2019-02-08 12:13:17

标签: 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)

    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!")

问题始于

temp = self.gray_img 
detectFaceOfImage函数中的

。我正在将temp传递给normalizeImages(),但是某种程度上,甚至变量gray_img都受此函数影响。 当我导出gray_img时,即使gray_img的内存没有任何改变,它也会显示规范化的临时图像。请帮我。我不知道为什么会这样。

1 个答案:

答案 0 :(得分:1)

如果数据是列表或任何其他对象,则需要深层副本。

看看这个:

>>> def mutate(data):
...   data[0]=101
...
>>> L=[1,2,3]
>>> temp=L
>>> mutate(temp)
>>> temp
[101, 2, 3]
>>> L
[101, 2, 3]

如果有

>>> L=[1,2,3]
>>> temp=list(L) #<--- deep copy here
>>> mutate(temp)

这会发生:

>>> temp
[101, 2, 3]
>>> L
[1, 2, 3]

如果您的类型不是list,则只需将其指定为深拷贝即可。