0

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!

2
  • 1
    Often the size 3 color channel is the last dimension, so the array would have shape (225, 400,3). Your array needs a transpose. Commented Dec 19, 2020 at 22:55
  • Yes, I agree with you about the cause but I did not know how to transpose. The answer below solved the problem! Thanks! Commented Dec 19, 2020 at 23:37

1 Answer 1

2

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

arr = np.moveaxis(arr , 0, -1)
Sign up to request clarification or add additional context in comments.

3 Comments

I was not aware of the "moveaxis" method. It solved my problem. Thanks! I have only one more question for this case. When I try to save it with OpenCV ( cv2.imwrite('cv2.png', arr) ), colors differ somehow. Do you have any idea about that?
sure. opencv defalt colors order is BGR. Yours are probably RGB so you need to swap them by arr[:,:,(2,1,0)]
My arrays are in RGB as you said. It was good information. Thank you for your clear explanations!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.