Unexpected image modification when using cv2.imread for image loading

Question:

I am trying to do some modifications to the image (‘some_image.jpeg’).
For that reason I am loading it into to variables: image_org and image_mod.
In image_mod i want to do modifications, image_org i want to keep unchanged for later comparizons.
After doing some changes to the image_mod (basically drawing some lines on it).
I am creating a new image which is a difference btween the modified one and the original one: image_diff = cv2.subtract(image_mod, image_org).
I calculate the difference into one number with: diff_num = cv2.sumElems(image_diff)[0] and save all 3 images into .png files.
I am expacting to obtain:
– image that is identical to original file (image_org)
– image that has additional lines on it (image_mod)
– image with lines only that were added to the image_mod (image_diff)
– diff_num to be a number, rather big number
However what i get:
– image_org is changed and looks exactlz the same as image_mod
– diff_num is equal to 0.0

I quess that i am making mistake in the first few lines of the code, however i can not understand how image_org is getting modified with my code. Please help how to fix it so i can get what i am expecitng to get.

import cv2

image_org = cv2.imread('some_image.jpeg',0)
image_mod = image_org

for i in range(10):
    cv2.line(image_mod,(100+i*5,0),(0+i*5,150),(255),1,16)

image_diff = cv2.subtract(image_mod, image_org)
diff_num = cv2.sumElems(image_diff)[0]

cv2.imwrite('test_org.png',image_org)
cv2.imwrite('test_mod.png',image_mod)
cv2.imwrite('test_dif.png',image_diff)

print(diff_num)
Asked By: KorwinNaSloniu

||

Answers:

image_org and image_mod are just two names for the same object.

You need to make a copy of your original image:

image_mod = image_org.copy()

image_mod will then be a different object.

Answered By: Thierry Lathuille
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.