简体   繁体   中英

Unexpected image modification when using cv2.imread for image loading

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM