简体   繁体   English

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

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

So I am trying to change the values of one RGB channel in cv2 by splitting it by pixel and then adding or substracting a value.所以我试图通过按像素拆分它然后添加或减去一个值来更改 cv2 中一个 RGB 通道的值。 This would make a pixel "greener" or "reder" in theory.这将使像素在理论上“更绿”或“更红”。 But instead it is not working.但相反,它不起作用。 Do you know what is the problem?你知道是什么问题吗? Original image:原图:

Desired Output所需 Output

Current Output当前Output

This is my code:这是我的代码:

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()

When you index with image[y,x] you're getting a 3-element list [b,g,r].当您使用 image[y,x] 进行索引时,您将获得一个 3 元素列表 [b,g,r]。 If you want to add 100 to the red channel then you can index the color directly and add the number image[y,x,2].如果你想给红色通道加 100 那么你可以直接索引颜色并添加数字 image[y,x,2]。

However, when you add scalar values directly to the colors like this, there's nothing protecting you from overflowing the UInt8 value.但是,当您像这样将标量值直接添加到 colors 时,没有什么可以保护您免于溢出 UInt8 值。 If it goes over 255 it'll wrap back around to zero.如果超过 255,它将回绕到零。 You can either manually do the overflow check yourself or use OpenCV's cv2.add() function.您可以自己手动进行溢出检查,也可以使用 OpenCV 的 cv2.add() function。

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);

Overflow Protected溢出保护

在此处输入图像描述

No Overflow Protection无溢出保护

在此处输入图像描述

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

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