简体   繁体   中英

How can I change the color of an image by using cv2?

Now, I got an image, and I want to change the color of it. Then, show the before and after

This is how I write

import numpy as np
import cv2

Original_img = cv2.imread('img.jpg')
New_img = Original_img

print(Original_img[0 , 20] , New_img[0 , 20])


New_img[0 , 20] = 0  #change the color of new

print( Original_img[0 , 20] , New_img[0 , 20])

But it turn out that both change. But, I only want the new one changes

Output:

[55 69 75] [55 69 75]
[0 0 0] [0 0 0]

This is a tricky one. It turns out that that your Original_img and New_img both refer to the same underlying object in Python. You need to make a copy to create a new object:

New_img = Original_img.copy()  # use copy function from numpy

Python lists behave this way too. Here is a simple annotated example using a interactive Python session:

>>> a = [1,2,3]
>>> b = a
>>> b
[1, 2, 3]
>>> b[1] = 3.1415927   # we think we are only changing b
>>> b
[1, 3.1415927, 3]      # b is changed
>>> a
[1, 3.1415927, 3]      # a is also changed

Same example, using copy()

>>> from copy import copy
>>> a = [1,2,3]
>>> b = copy(a)  # now we copy a
>>> b
[1, 2, 3]
>>> b[1] = 3.1415927
>>> b
[1, 3.1415927, 3] # b is changed
>>> a
[1, 2, 3]         # a is unchanged!

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