Justin
Justin

Reputation: 145

Printing RGB channels

If I have an RGB image i.e.: img_RGB and I print one of the channels. What is the difference exactly when doing print(img_RGB[:,:,2]) or print(img_RGB[:,:,1])? Because I tried it, and I obtained the same matrix. To my knowledge I am printing the values of the blue channel however I am not sure what difference it makes if I print the matrix when using either '1' or '2'

Image being used: [1]: https://i.sstatic.net/dKIf4.jpg

Upvotes: 1

Views: 648

Answers (1)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

With your image it seems most of the pixel have same value across all the channels (at least in B and G), that is why while printing you do not see the differences, because the number of different values are so few. We can inspect this in the following way:

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

Checking this result, one might be tempted to say that all are equal, however, if we look closely, that is not the case:

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

So printing an image array of shape (1351, 1982) is not a good idea to check for differences.

Upvotes: 1

Related Questions