Skip to main content
 首页 » 编程设计

python之如何在 Python 中组合 2d 和 3d numpy 数组

2024年11月24日8cyq1162

我有以下数组,它将图像表示为三色 numpy 数组。

array([[[165, 173, 184], 
        [170, 178, 189], 
        [171, 179, 190], 
        ..., 
        [145, 162, 180], 
        [140, 157, 175], 
        [142, 159, 177]], 
 
       [[169, 177, 188], 
        [170, 178, 189], 
        [169, 177, 188], 
        ..., 
        [152, 169, 187], 
        [149, 166, 184], 
        [143, 160, 178]], 
 
       [[170, 178, 189], 
        [169, 177, 188], 
        [168, 176, 187], 
        ..., 
        [143, 160, 178], 
        [144, 161, 179], 
        [142, 159, 177]], 
 
       ..., 
 
       [[  5,  13,   2], 
        [  5,  13,   2], 
        [  8,  16,   5], 
        ..., 
        [ 31,  27,  16], 
        [ 28,  24,  13], 
        [ 27,  23,  12]], 
 
       [[  0,   8,   0], 
        [  1,   9,   0], 
        [  8,  16,   3], 
        ..., 
        [ 30,  26,  15], 
        [ 19,  15,   4], 
        [ 13,   9,   0]], 
 
       [[  4,  12,   1], 
        [  3,  11,   0], 
        [  6,  14,   1], 
        ..., 
        [ 36,  32,  21], 
        [ 27,  23,  12], 
        [ 22,  18,   7]]], dtype=uint8) 

这是(4032, 3024, 3)

同一张图片灰度化成这样

array([[0.67058825, 0.6901961 , 0.69411767, ..., 0.61960787, 0.6       , 
        0.60784316], 
       [0.6862745 , 0.6901961 , 0.6862745 , ..., 0.64705884, 0.63529414, 
        0.6117647 ], 
       [0.6901961 , 0.6862745 , 0.68235296, ..., 0.6117647 , 0.6156863 , 
        0.60784316], 
       ..., 
       [0.03529412, 0.03529412, 0.04705882, ..., 0.10196079, 0.09019608, 
        0.08627451], 
       [0.01568628, 0.01960784, 0.04705882, ..., 0.09803922, 0.05490196, 
        0.03529412], 
       [0.03137255, 0.02745098, 0.03921569, ..., 0.12156863, 0.08627451, 
        0.06666667]], dtype=float32) 
 

这是(4032, 3024)

我想在单个数组中表示颜色和灰度,例如 (4032, 3024, 4) 怎么办? 或者有没有办法同时表达颜色和灰度?

请您参考如下方法:

如果我没理解错的话,numpy.dstack正是您想要的。

This is equivalent to concatenation along the third axis
...
This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis).

image = np.arange(12).reshape([2, 2, 3]) 
grey = np.arange(4).reshape([2, 2])  
stacked  = np.dstack([image, grey]) 
 
stacked.shape 
# (2, 2, 4) 

堆叠:

   array([[ 
      [ 0,  1,  2,  0], 
      [ 3,  4,  5,  1]], 
      [[ 6,  7,  8,  2], 
      [ 9, 10, 11,  3]]])