从三通道图像中获取第二个通道作为 Numpy 数组

Get the second channel from a three channels image as a Numpy array

我正在使用 Python 3.7.7.

我有一个三通道图像作为具有这种形状的 Numpy 数组:(200, 200, 3)

因为它太大了,所以我试着猜测我要用这个例子做什么:

import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print(a[1]) # Output [4, 5, 6]

但我不确定我做的是否正确。

我需要做什么才能从图像数组中获取第二个通道(输出形状 (200, 200, 1))?

如果您问的是使用约定,在机器学习的图像处理中,我通常会看到每个图像都被压平,因此每个图像都是一长行,按 row-major 顺序,然后是通道顺序。 Numpy 有 obj.flatten() 命令来简化这件事。然后要检索中间通道,可以使用 Numpy 切片或索引。每个处理的批次都有很多图像(行),每个图像是一个很长的扁平行。

示例:

b = a.flatten()  
print(b)  
# output array([1, 2, 3, 4, 5, 6, 7, 8, 9])
channel2 = b[3:6]  
print(channel2) 
# output array([4, 5, 6])

对于其他用例,可能有不同的约定。

更长的示例,使用具有 3 个通道的 3x3 图像阵列。
请注意,数值按 row-major 顺序排列,然后是通道顺序。

img_a = np.arange(0, 27).reshape(3, 3, 3) 
''' output 
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])
'''  
# Flatten into one long row  
row_a = img_a.flatten()
# output array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
#       17, 18, 19, 20, 21, 22, 23, 24, 25, 26])

# Select middle channel using Numpy slicing    
channel_mid = row_a[9:18] 
# output array([ 9, 10, 11, 12, 13, 14, 15, 16, 17])

# Convert middle channel back into a matrix shape (if needed).
matrix_mid = channel_mid.reshape(3, 3)
''' output 
array([[ 9, 10, 11],
       [12, 13, 14],
       [15, 16, 17]])
'''