Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read image data from a URL in Python?

People also ask

How do you download an image from a URL in Python?

Many developers consider it a convenient method for downloading any file type in Python. Once you've imported those files, create a url variable that is set to an input statement asking for the image URL. In the next line of code, implement the get() method from the requests module to retrieve the image.

How do I open an image URL?

On your computer, go to images.google.com. Search for the image. In Images results, click the image. At the top of your browser, click the address bar to select the entire URL.


In Python3 the StringIO and cStringIO modules are gone.

In Python3 you should use:

from PIL import Image
import requests
from io import BytesIO

response = requests.get(url)
img = Image.open(BytesIO(response.content))

Using a StringIO

import urllib, cStringIO

file = cStringIO.StringIO(urllib.urlopen(URL).read())
img = Image.open(file)

The following works for Python 3:

from PIL import Image
import requests

im = Image.open(requests.get(url, stream=True).raw)

References:

  • https://github.com/python-pillow/Pillow/pull/1151
  • https://github.com/python-pillow/Pillow/blob/master/CHANGES.rst#280-2015-04-01

Using requests:

from PIL import Image
import requests
from StringIO import StringIO

response = requests.get(url)
img = Image.open(StringIO(response.content))

Python 3

from urllib.request import urlopen
from PIL import Image

img = Image.open(urlopen(url))
img

Jupyter Notebook and IPython

import IPython
url = 'https://newevolutiondesigns.com/images/freebies/colorful-background-14.jpg'
IPython.display.Image(url, width = 250)

Unlike other methods, this method also works in a for loop!


Use StringIO to turn the read string into a file-like object:

from StringIO import StringIO
import urllib

Image.open(StringIO(urllib.requests.urlopen(url).read()))

For those doing some sklearn/numpy post processing (i.e. Deep learning) you can wrap the PIL object with np.array(). This might save you from having to Google it like I did:

from PIL import Image
import requests
import numpy as np
from StringIO import StringIO

response = requests.get(url)
img = np.array(Image.open(StringIO(response.content)))