如何用cv2改变Python中一个RGB通道的值?

How to change the value of one RGB channel in Python with cv2?

所以我试图通过按像素拆分它然后添加或减去一个值来更改 cv2 中一个 RGB 通道的值。这将使像素在理论上“更绿”或“更红”。但是它不起作用。你知道问题出在哪里吗? Original image:

Desired Output

Current Output

这是我的代码:

import numpy
import dlib
import cv2

image = cv2.imread("image.jpeg")
num = 1

x_max, y_max, rgba = image.shape

for x in range(x_max):
    num += 1
    for y in range(y_max):
        b, g, r = image[x, y]
        image[x:x_max, y:y_max] = b, g+100, r


while True:
    cv2.imshow("Output", image)
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

当您使用 image[y,x] 建立索引时,您会得到一个 3 元素列表 [b,g,r]。如果你想给红色通道加 100 那么你可以直接索引颜色并添加数字 image[y,x,2].

但是,当您像这样将标量值直接添加到颜色时,没有任何东西可以防止您溢出 UInt8 值。如果它超过 255,它将回到零。您可以自己手动进行溢出检查,也可以使用 OpenCV 的 cv2.add() 函数。

import cv2
import numpy as np

# load image
img = cv2.imread("test.jpg");
orig = np.copy(img);

# create blank image
red = np.zeros_like(img);

# fill with red
red[:,:] = [0,0,100]; # (b,g,r)

# add to image (has overflow protection, values are clamped between [0,255])
img = cv2.add(img, red);

# show
cv2.imshow("Original", orig);
cv2.imshow("OpenCV Add", img);
cv2.waitKey(0);

# do it with loops
img = np.copy(orig);
unprotected = np.copy(orig);
height, width = img.shape[:2];

# loop through and add 100 red to each pixel
# WARNING, this method has no automatic overflow protection
# if the red value goes over 255 then it'll wrap back around to 0 (i.e. 200 + 100 will give 45)
for y in range(height):
    for x in range(width):
        # overflow check
        if 100 + img[y,x,2] > 255:
            # saturate value
            img[y,x,2] = 255;
        else:
            # add normally
            img[y,x,2] += 100;

        # always add to unprotected image
        unprotected[y,x,2] += 100;

# show
cv2.imshow("Looping Add", img);
cv2.imshow("Unprotected", unprotected);
cv2.waitKey(0);

溢出保护

无溢出保护