【问题标题】:Get the second channel from a three channels image as a Numpy array从三通道图像中获取第二个通道作为 Numpy 数组
【发布时间】:2020-08-04 14:25:13
【问题描述】:

我正在使用 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))?

【问题讨论】:

标签: python numpy python-3.7


【解决方案1】:

如果您询问使用约定,在机器学习的图像处理中,我通常会看到每个图像被展平,以便每个图像是一个长行,按行优先顺序,然后是通道顺序。 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 图像阵列的更长示例。
请注意,数值按行优先顺序,然后是通道顺序。

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

【讨论】:

    猜你喜欢
    • 2018-03-21
    • 2019-09-14
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 2017-10-10
    相关资源
    最近更新 更多