Search code examples
arrayspython-3.xnumpypython-requestspython-imageio

Converting the response of Python get request(jpg content) in Numpy Array


The workflow of my function is the following:

  • retrieve a jpg through python get request
  • save image as png (even though is downloaded as jpg) on disk
  • use imageio to read from disk image and transform it into numpy array
  • work with the array

This is what I do to save:

response = requests.get(urlstring, params=params)
      if response.status_code == 200:
            with open('PATH%d.png' % imagenumber, 'wb') as output:
                output.write(response.content)

This is what I do to load and transform png into np.array

imagearray = im.imread('PATH%d.png' % imagenumber)

Since I don't need to store permanently what I download I tried to modify my function in order to transform the response.content in a Numpy array directly. Unfortunately every imageio like library works in the same way reading a uri from the disk and converting it to a np.array.

I tried this but obviously it didn't work since it need a uri in input

response = requests.get(urlstring, params=params)
imagearray = im.imread(response.content))

Is there any way to overcome this issue? How can I transform my response.content in a np.array?


Solution

  • imageio.imread is able to read from urls:

    import imageio
    
    url = "https://example_url.com/image.jpg"
    
    # image is going to be type <class 'imageio.core.util.Image'>
    # that's just an extension of np.ndarray with a meta attribute
    
    image = imageio.imread(url)
    

    You can look for more information in the documentation, they also have examples: https://imageio.readthedocs.io/en/stable/examples.html