为什么应用同一通道三次会产生黑白图像?

2024-09-28 13:29:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用opencv进行颜色交换的实验。在下面的代码片段中,结果与我的预期非常接近

import cv2

color = cv2.imread("lohri.jpg")
b,g,r = cv2.split(color)
swap = cv2.imwrite("swap.jpg", cv2.merge((r,g,b)))

正如你在上面看到的,我已经交换了红色和蓝色的两个颜色通道。但如果我只应用一个通道,如下所示:

swap = cv2.imwrite("swap.jpg", cv2.merge((b,b,b)))

它会产生黑白图像。我不明白为什么。有人能帮我理解吗

以下是应用同一通道三次后得到的图像

enter image description here

原始图像看起来像: enter image description here

无论选择哪个通道(r、g、b),都会发生这种情况


Tags: 代码图像import颜色mergecv2opencvcolor
1条回答
网友
1楼 · 发布于 2024-09-28 13:29:33

这里有几件事需要理解

首先,我们应该讨论颜色编码是如何工作的Source article. Highly recommend reading it

A digital photograph consists of pixels, a pixel being a colored dot, the smallest element of the image. Each pixel has one and only one color.

我的

这里的主要内容是,最终的图像是不同通道的组合(可以这么说)。更多关于这一点(稍后)为每一个像素

Multiple ways of color coding exist. The most prominent of these is RGB. So there we are: RGB. R means: red. G means: green. B means: blue. The RGB color coding assumes that every color has three components: red, green and blue. Believe it or not, all colors that humans can see can be composed from a combination of red, green and blue.

这里需要理解的重要一点是,R、G、B只是表示每个像素的“组合”的一种方式。正是这种组合给了我们在图像中看到的颜色

第三个,在RGB中,数字表示该颜色/通道分量的“数量”。0表示:无,255表示:最大金额

第四

First observation: In the RGB way of color coding, the higher the numbers, the lighter the corresponding color.

Second observation: When all three of R, G and B are equal, we get a neutral color: white, grey or black.

理解这一部分非常重要。由于R、G和B值仅表示组件,因此必须根据每个组件的“数量”对它们进行合并。如果它们的数量相等,它们都会产生从黑到白(通常称为灰度)的阴影。黑/白度取决于每个通道的实际数量,0为黑色,255为白色,其他介于两者之间。理解这一点很重要,这意味着图像仍然可以具有3个R、G、B分量,但对于灰度像素,它们都被设置为相同的值

现在,深入到它的编码方面,重要的是要认识到,数字只是,纯数字

import cv2

color = cv2.imread("lohri.jpg")
b,g,r = cv2.split(color)

这里,b、g和r不再是什么特殊的,它们只是存储数字的矩阵,每个像素一个。我可以很好地为他们写下不同的名字,如下所示:

import cv2

color = cv2.imread("lohri.jpg")
apple,mango,orange = cv2.split(color) #perfectly valid, although confusing

很明显,名字就是那个,名字。只有图像中的“组合”赋予了它们任何意义。那么,当你做这一步的时候

swap = cv2.imwrite("swap.jpg", cv2.merge((b,b,b)))

我可以这样写

swap = cv2.imwrite("swap.jpg", cv2.merge((some_random_matrix,some_random_matrix,some_random_matrix)))

或者像这样,

swap = cv2.imwrite("swap.jpg", cv2.merge((apple,apple,apple)))

需要理解的重要一点是:变量名b本身没有任何意义,它只是一个数字矩阵。使用合并功能并将每个R、G和B通道设置为相同的矩阵时,可以有效地为每个R、G、B值为每个像素指定相同的值。正如我们以前所知道的,当像素的每个“通道”具有相同的值时,“组合”总是从黑到白(或灰度)

最后,如果您希望它看起来是blue而不是灰度,那么您现在可以猜出正确的方法

正确的方法是将值保留在蓝色通道中,但为每个像素将其他通道设置为0。将所有通道设置为相同的值并不能使您获得“更多特定颜色”,因为该值本身没有任何意义,它只是每个通道上的值的“组合”

color = cv2.imread('lohri.jpg')

new_image = color.copy()
# set green and red channels to 0
new_image[:, :, 1] = 0
new_image[:, :, 2] = 0
cv2.imwrite("only_blue.jpg", new_image)

相关问题 更多 >

    热门问题