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

2019-01-02 16:55发布

What I'm trying to do is fairly simple when we're dealing with a local file, but the problem comes when I try to do this with a remote URL.

Basically, I'm trying to create a PIL image object from a file pulled from a URL. Sure, I could always just fetch the URL and store it in a temp file, then open it into an image object, but that feels very inefficient.

Here's what I have:

Image.open(urlopen(url))

It flakes out complaining that seek() isn't available, so then I tried this:

Image.open(urlopen(url).read())

But that didn't work either. Is there a Better Way to do this, or is writing to a temporary file the accepted way of doing this sort of thing?

8条回答
与君花间醉酒
2楼-- · 2019-01-02 17:05

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)))
查看更多
泛滥B
3楼-- · 2019-01-02 17:05

This works on Python 3.6 as well...

from urllib.request import urlopen
from PIL import Image

img = Image.open(urlopen(url))
img
查看更多
怪性笑人.
4楼-- · 2019-01-02 17:09

select the image in chrome, right click on it, click on Copy image address, paste it into a str variable (my_url) to read the image:

import shutil
import requests

my_url = 'https://www.washingtonian.com/wp-content/uploads/2017/06/6-30-17-goat-yoga-congressional-cemetery-1-994x559.jpg'
response = requests.get(my_url, stream=True)
with open('my_image.png', 'wb') as file:
    shutil.copyfileobj(response.raw, file)
del response

open it;

from PIL import Image

img = Image.open('my_image.png')
img.show()
查看更多
公子世无双
5楼-- · 2019-01-02 17:12

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))
查看更多
春风洒进眼中
6楼-- · 2019-01-02 17:22

you could try using a StringIO

import urllib, cStringIO

file = cStringIO.StringIO(urllib.urlopen(URL).read())
img = Image.open(file)
查看更多
流年柔荑漫光年
7楼-- · 2019-01-02 17:25

I use the requests library. It seems to be more robust.

from PIL import Image
import requests
from StringIO import StringIO

response = requests.get(url)
img = Image.open(StringIO(response.content))
查看更多
登录 后发表回答