numpy 3d矩阵到2d矩阵

时间:2019-03-06 18:07:03

标签: python numpy

你好,我有这个当前矩阵:

[[[223 215 213]
  [222 213 214]
  [222 213 214]
  ...
  [229 223 223]
  [229 223 223]
  [229 223 223]]

 [[220 211 212]
  [220 211 212]
  [221 212 213]
  ...
  [229 220 221]
  [229 220 221]
  [227 221 221]]

 [[219 210 211]
  [219 210 213]
  [220 209 213]
  ...
  [229 220 221]
  [229 220 221]
  [229 220 221]]

 ...

 [[ 31  38  93]
  [ 48  54 112]
  [ 95 105 167]
  ...
  [142 147 202]
  [148 151 202]
  [135 141 189]]

 [[ 33  42 101]
  [ 64  74 133]
  [ 97 108 170]
  ...
  [140 146 198]
  [142 148 200]
  [131 137 189]]

 [[ 44  56 116]
  [ 91 101 162]
  [ 98 109 171]
  ...
  [139 145 195]
  [129 135 187]
  [125 130 186]]]

我需要将其转换为三个分别代表图像的R,G,B值的2d矩阵

这是我尝试的代码,这是我对R数组的结果:

R = img1.transpose(2,0,1).reshape(300, -1)

结果:

[[223 222 222 ... 229 229 229]
 [220 219 217 ... 230 230 229]
 [221 222 222 ... 229 229 229]
 ...
 [ 96  73  71 ... 196 190 190]
 [103  94 106 ... 196 209 197]
 [ 93 112 167 ... 195 187 186]]

应该是什么:

[[223 222 222 ... 229 229 229]
 [220 220 221 ... 229 229 227]
 [219 219 220 ... 229 229 229]
 ...
 [ 31  48  95 ... 142 148 135]
 [ 33  64  97 ... 140 142 131]
 [ 44  91  98 ... 139 129 125]] 

任何有关如何达到此格式的帮助将不胜感激!

3 个答案:

答案 0 :(得分:0)

您可以使用slices沿特定轴提取。

我相信在您的特定情况下,您应该这样做:

red = data[:, :, 0] #Take all values along the first dimension, all values along the second dimension and only the first value along the third dimension
green = data[:, :, 1]
blue = data[:, :, 2]

答案 1 :(得分:0)

您可以使用切片。

 arr = np.array([[[1,2,3],[4,5,6],[7,8,9]],[[1,2,3],[4,5,6],[7,8,9]],[[1,2,3],[4,5,6],[7,8,9]]])
    R = arr[:,:,0]
    G = arr[:,:,1]
    B = arr[:,:,2]

答案 2 :(得分:0)

考虑您有一个名为img的numpy数组

print img.shape

给予

(64,64,3)

,您想为每个chanell创建三个变量R,G和B,如下所示:

R,G,B = img[:,:,0], img[:,:,1], img[:,:,2]

print "R:" R.shape, "G:", G.shape, "B:", B.shape

赋予形状

R: (64,64) G: (64,64) B: (64,64)