Transform media image to numpy array

Hi! I am working on an app that uploads an image using a file loader and then updates it by changing some of the pixels. When updating the image, I need to transform it into an numpy array so I can update the RGB values of the pixels. However, when I try to do that with a media object, I encounter the following problem:

img = np.array(media_obj)

“IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed”

Apparently the array does not have the dimensions I expected, so I was wondering if someone knows how to transform the media object back to a multidimensional array?

Numpy’s array() function won’t know anything about Anvil’s objects. Nor should it be expected to. They’re two independent bodies of code.

I tend to break up the R&D into 3-4 steps:

  1. Look up the parameters that the function (array()) expects.
  2. Then look up the features that the data-container (Anvil’s Media Object) offers.
  3. See if I can find a meaningful match between the two. If so, great! The coding will be straightforward.
  4. Otherwise, search the Tutorials and this Forum for related examples. I’m fairly sure you’ll find something close to what you want.
1 Like

Hey, I could not find any examples but I was able to solve the issue by using the method .get_bytes() and then translating that to an array using:

import numpy as np
from io import BytesIO
from PIL import Image

np.array(Image.open(BytesIO(bytes)))

Thank you for your answer!

1 Like