Python - 如何从 URL 读取图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40911170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - how to read an image from a URL?
提问by connoraw
I am completely new to Python and I'm trying to figure out how to read an image from a URL.
我对 Python 完全陌生,我正试图弄清楚如何从 URL 读取图像。
Here is my current code:
这是我当前的代码:
from PIL import Image
import urllib.request, io
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urllib.request.urlopen(URL) as url:
s = url.read()
Image.open(s)
I get the following error:
我收到以下错误:
C:\python>python image.py
Traceback (most recent call last):
File "image.py", line 8, in <module>
Image.open(s)
File "C:\Anaconda3\lib\site-packages\PIL\Image.py", line 2272, in open
fp = builtins.open(filename, "rb")
ValueError: embedded null byte
I have no idea what any of this means. What am I doing wrong?
我不知道这意味着什么。我究竟做错了什么?
回答by furas
Image.open()
expects filename or file-like object - not file data.
Image.open()
需要文件名或类似文件的对象 - 而不是文件数据。
You can write image locally - ie as "temp.jpg"
- and then open it
您可以在本地写入图像 - 即作为"temp.jpg"
- 然后打开它
from PIL import Image
import urllib.request
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urllib.request.urlopen(URL) as url:
with open('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
或者您可以使用io
模块在内存中创建类似文件的对象
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()
回答by ngub05
Here's how to read an image from a URL using scikit-image
以下是使用scikit-image从 URL 读取图像的方法
from skimage import io
io.imshow(io.imread("http://www.w3schools.com/css/trolltunga.jpg"))
io.show()
Note: io.imread()returns a numpy array
注意:io.imread()返回一个 numpy 数组
回答by mikeqfu
To begin with, you may download the image to your current working directory first
首先,您可以先将图像下载到您当前的工作目录
from urllib.request import urlretrieve
url = '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 format
print(img.size)
print(img.format)
img.show()
回答by caspillaga
As suggested in this stack overflow answer, you can do something like this:
正如此堆栈溢出答案中所建议的,您可以执行以下操作:
import urllib, cStringIO
from PIL import Image
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:
然后你可以自由地使用你的图像。例如,您可以将其转换为 numpy 数组:
img_npy = np.array(img)