First, my 3 separate scenarios and my input image

enter image description here

Scenario 1: Copying input image onto new variable by " = "

a = cv2.imread("/content/consec2.jpg")
b = a

b [b < 200] = 0 #Some random change to an image

plt.imshow(a, cmap='gray')

Image Displayed: ("changed" image) enter image description here

Scenario 2: Copying input image onto new variable by .copy() method

a = cv2.imread("/content/consec2.jpg")
b = a.copy()

b [b < 100] = 0 #Same random change to the image as in scenario 1

plt.imshow(a, cmap='gray')

Image Displayed: The original input image

Scenario 3: Normal calculation (Disregard the image here)

a = 10
b = a
print (a)

Result: the printed value comes out to 10 (This scenario is just for extra refernce).

QUESTION: Why are scenario 1 and scenario 2 giving differnet results? Shouldn't the " = " and .copy() function the same way in this case?


1 Answer 1


In scenario 1, the underlying memory is used for both Mat a and Mat b, so when you change b, you end up changing a as well, i.e. it's just a reference to the underlying Mat that is copied. From the opencv docs: https://docs.opencv.org/4.x/d6/d6d/tutorial_mat_the_basic_image_container.html

"All the above objects, in the end, point to the same single data matrix and making a modification using any of them will affect all the other ones as well."

In scenario 2, you have created a new Mat through the call to a.copy() and initialized the underlying memory, so changes to b won't impact a.

This is the same for all objects in python btw, it has nothing to do specifically with opencv. https://docs.python.org/3/library/copy.html



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.