Python 打印RGB通道

Python 打印RGB通道,python,image,numpy,opencv,rgb,Python,Image,Numpy,Opencv,Rgb,如果我有一个RGB图像,即:img\u RGB并打印其中一个通道。在执行打印(img_RGB[:,:,2])或打印(img_RGB[:,:,1])时,具体的区别是什么? 因为我试过了,得到了相同的矩阵。据我所知,我正在打印蓝色通道的值,但是我不确定当使用'1'或'2' 正在使用的图像: [1] :对于您的图像,似乎大多数像素在所有通道中都具有相同的值(至少在B和G中),这就是为什么在打印时您看不到差异,因为不同值的数量非常少。我们可以通过以下方式进行检查: >>> img =

如果我有一个RGB图像,即:
img\u RGB
并打印其中一个通道。在执行
打印(img_RGB[:,:,2])
打印(img_RGB[:,:,1])
时,具体的区别是什么? 因为我试过了,得到了相同的矩阵。据我所知,我正在打印蓝色通道的值,但是我不确定当使用
'1'
'2'

正在使用的图像:
[1] :

对于您的图像,似乎大多数像素在所有通道中都具有相同的值(至少在
B
G
中),这就是为什么在打印时您看不到差异,因为不同值的数量非常少。我们可以通过以下方式进行检查:

>>> img = cv2.imread(fname, -1);img_RGB = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
>>> img_RGB[:,:,2] == img_RGB[:,:,1]

array([[ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       ...,
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True]])
检查这一结果时,人们可能会说所有人都是平等的,但是,如果我们仔细观察,情况并非如此:

>>> (img_RGB[:,:,2] == img_RGB[:,:,1]).all()
False

# So there are some values that are not identical
# Let's get the indices

>>> np.nonzero(img_RGB[:,:,2] != img_RGB[:,:,1])
(array([  16,   16,   16, ..., 1350, 1350, 1350], dtype=int64),
 array([  83,   84,   85, ..., 1975, 1976, 1977], dtype=int64))

# So these are the indices, where :
# first element of tuple is indices along axis==0
# second element of tuple is indices along axis==1

# Now let's get values at these indices:
>>> img_RGB[np.nonzero(img_RGB[:,:,2] != img_RGB[:,:,1])]
#        R    G    B
array([[254, 254, 255],
       [252, 252, 254],
       [251, 251, 253],
       ...,
       [144, 144, 142],
       [149, 149, 147],
       [133, 133, 131]], dtype=uint8)
# As can be seen, values in `G` and `B` are different in these, essentially `B`.
# Let's check for the first index, `G` is:
>>> img_RGB[16, 83, 1]
254
# And `B` is:
>>> img_RGB[16, 83, 1]
255

因此,打印形状为
(13511982)
的图像数组并不是检查差异的好方法。

img_RGB[0,0]返回什么?Python没有内置图像类型。您的
img\u RGB
是什么数据类型?如果是numpy数组,请至少相应地标记您的问题。@martineau抱歉,
img_RGB
正在加载一个.jpg图像,该图像已从GBR转换为RGB,如图所示:
img=cv2.imread('WellPlate.jpg',-1)img_RGB=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
@Sayandip Dutta,正如预期的那样,由于图像是RGB图像,因此它返回[0 0 0]@Jason即使格式是RGB,从您的问题来看,似乎所有通道都具有相同的值。因此,无论通过1还是2访问,都没有可见的更改。现在在第一个像素处,这个假设似乎是正确的。现在你要检查所有的像素是否都是这样。您可以尝试以下操作:
(img_RGB==img_RGB.max(-1,keepdims=True)).all(-1).all()
,并检查它是否为真。如果是,那么代码没有问题,只是所有通道都有相同的值。好的,我想我理解了为什么在执行
print(img_RGB[:,:,2])
print(img_RGB[:,:,1])
时我得到了相同的结果。但是,为了澄清,如果我需要像我在这里尝试做的那样只打印蓝色通道,假设图像在通道中具有不同的值,我如何知道使用哪个通道是
'1'
还是
'2'
?或者这取决于我需要的结果吗?
OpenCV
默认情况下读取
BGR
中的图像,因此在不进行任何转换的情况下,您需要访问
img_RGB[:,:,0]
才能获得蓝色,因为
BGR->蓝绿红->0 1 2
。当您转换到
RGB
时,您可以访问
2
,以获得蓝色,
RGB->0 1 2