简体   繁体   English

如何使用 cv2 更改图像的颜色?

[英]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: 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.事实证明,您的 Original_img 和 New_img 都引用了 Python 中相同的底层 object。 You need to make a copy to create a new object:您需要进行复制以创建新的 object:

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

Python lists behave this way too. Python 列表的行为也是如此。 Here is a simple annotated example using a interactive Python session:这是一个使用交互式 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()同样的例子,使用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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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