Skip to content Skip to sidebar Skip to footer

Python - How To Read An Image From A Url?

I am completely new to Python and I'm trying to figure out how to read an image from a URL. Here is my current code: from PIL import Image import urllib.request, io URL = 'http://

Solution 1:

Image.open() expects filename or file-like object - not file data.

You can write image locally - ie as "temp.jpg" - and then open it

from PIL import Image
import urllib.request

URL = 'http://www.w3schools.com/css/trolltunga.jpg'with urllib.request.urlopen(URL) as url:
    withopen('temp.jpg', 'wb') as f:
        f.write(url.read())

img = Image.open('temp.jpg')

img.show()

Or you can create file-like object in memory using io module

from PIL import Image
import urllib.request
import io

URL = 'http://www.w3schools.com/css/trolltunga.jpg'with urllib.request.urlopen(URL) as url:
    f = io.BytesIO(url.read())

img = Image.open(f)

img.show()

Solution 2:

Here's how to read an image from a URL using scikit-image

from skimage import ioio.imshow(io.imread("http://www.w3schools.com/css/trolltunga.jpg"))
io.show()

Note: io.imread() returns a numpy array

Solution 3:

To begin with, you may download the image to your current working directory first

from urllib.request importurlretrieveurl='http://www.w3schools.com/css/trolltunga.jpg'
urlretrieve(url, 'pic.jpg')

And then open/read it locally:

from PIL import Image
img = Image.open('pic.jpg')

# For example, check image size and formatprint(img.size)
print(img.format)

img.show()

Solution 4:

As suggested in this stack overflow answer, you can do something like this:

import urllib, cStringIO
fromPILimportImage

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

Then you can use your image freely. For example, you can convert it to a numpy array:

img_npy = np.array(img)

Post a Comment for "Python - How To Read An Image From A Url?"