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

2024-10-04 03:26:15 发布

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

我有以下数组,它将图像表示为三色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)怎么办? 或者有没有一种方法可以同时表达颜色和花格呢?你知道吗


Tags: 方法图像numpy颜色数组array照片灰度
1条回答
网友
1楼 · 发布于 2024-10-04 03:26:15

如果我理解正确,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)

stacked

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

相关问题 更多 >