Numpy 3d矩阵到2d矩阵

问题描述 投票:0回答:3

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

[[[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]]]

我需要把它变成三个独立的2d矩阵,代表图像的R,G,B值

这是我试过的代码,这里只是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]] 

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

python numpy
3个回答
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]

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]

0
投票

考虑你有numpy数组名为img

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)
© www.soinside.com 2019 - 2024. All rights reserved.