简体   繁体   中英

Numpy 3d Matrix to 2d Matrix

Hello I have this current matrix:

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

And I need to turn it into three separate 2d Matrices representing R, G, B values of an Image

Here's the code I tried and here's my result for just the R array:

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

Result:

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

What it should be:

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

Any help on how to reach this format would be appreciated!

You can use slices to extract along specific axes.

I believe in your particular case, you should do:

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]

you can use slicing.

 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]

consider you have numpy array named img

print img.shape

gives

(64,64,3)

and you want to create three variables R, G and B for each chanell as matrix so:

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

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

gives the shapes

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM