bbasaran
bbasaran

Reputation: 396

Saving NumPy RGB array as an image fails because of the array shape

I have a bunch of arrays of frames with the shape of (3, 225, 400) that were obtained from the screen buffer. I have trouble while saving them as RGB png images because of the shapes.

> arr = np.load("frame134.npy") 
> print(arr)

[[[63 47 63 ... 47 47 27]
  [63 47 39 ... 47 55 35]
  [63 47 39 ... 55 55 47]
  ...
  [91 35 35 ... 79 79 79]
  [91 35 63 ... 79 79 79]
  [55 63 63 ... 79 79 79]]

 [[71 47 47 ... 55 55 27]
  [71 47 39 ... 55 63 43]
  [71 47 39 ... 63 63 55]
  ...
  [99 35 35 ... 79 79 79]
  [99 35 71 ... 79 79 79]
  [63 71 71 ... 79 79 79]]

 [[43 47 23 ... 31 31 27]
  [43 47 39 ... 31 39 15]
  [43 47 39 ... 39 39 31]
  ...
  [71 35 35 ... 79 79 79]
  [71 35 43 ... 79 79 79]
  [39 43 43 ... 79 79 79]]]

When I try to save it by using PIL:

im = Image.fromarray(arr, "RGB")
im.save("tmp.png")

The result is as follows:

ss1

or, if I use matplotlib:

> plt.imsave('tmp.png', arr)
ValueError: Third dimension must be 3 or 4

How can I resize my array to make it able to be saved properly? Thanks!

Upvotes: 0

Views: 477

Answers (1)

Lior Cohen
Lior Cohen

Reputation: 5735

You will have to move your first axis to be the third. This can be done by

arr = np.moveaxis(arr , 0, -1)

Upvotes: 2

Related Questions