打印RGB通道

2024-09-30 16:30:57 发布

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

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

正在使用的图像: [1] :https://i.stack.imgur.com/dKIf4.jpg


Tags: https图像comimgstack矩阵rgb蓝色
1条回答
网友
1楼 · 发布于 2024-09-30 16:30:57

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

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

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

相关问题 更多 >