【发布时间】:2012-08-24 20:18:11
【问题描述】:
这一定很简单,但是如果不使用 urllib 模块并手动获取远程文件,我现在不知道该怎么做
我想用远程图像覆盖绘图(比如说“http://matplotlib.sourceforge.net/_static/logo2.png”),imshow() 和 imread() 都不能加载图像。
你知道哪个函数可以加载远程图像吗?
【问题讨论】:
标签: matplotlib
这一定很简单,但是如果不使用 urllib 模块并手动获取远程文件,我现在不知道该怎么做
我想用远程图像覆盖绘图(比如说“http://matplotlib.sourceforge.net/_static/logo2.png”),imshow() 和 imread() 都不能加载图像。
你知道哪个函数可以加载远程图像吗?
【问题讨论】:
标签: matplotlib
确实很简单:
import urllib2
import matplotlib.pyplot as plt
# create a file-like object from the url
f = urllib2.urlopen("http://matplotlib.sourceforge.net/_static/logo2.png")
# read the image file in a numpy array
a = plt.imread(f)
plt.imshow(a)
plt.show()
【讨论】:
urllib而不是urllib2并调用urllib.request.urlopen而不是urllib2.urlopen。
这适用于我在带有 python 3.5 的笔记本中:
from skimage import io
import matplotlib.pyplot as plt
image = io.imread(url)
plt.imshow(image)
plt.show()
【讨论】:
ValueError: invalid PNG header 的 urllib2 解决方案,但这对我来说效果很好
pip install scikit-image
你可以用这段代码做到这一点;
from matplotlib import pyplot as plt
a = plt.imread("http://matplotlib.sourceforge.net/_static/logo2.png")
plt.imshow(a)
plt.show()
【讨论】:
URLError: <urlopen error unknown url type: s3>
pyplot.imread 的 URL 是 deprecated
不推荐使用传递 URL。请打开网址阅读并通过 结果到枕头,例如和 np.array(PIL.Image.open(urllib.request.urlopen(url))).
Matplotlib 建议改用 PIL。我更喜欢按照SciPy 的建议使用imageio:
imread 在 SciPy 1.0.0 中已弃用,并将在 1.2.0 中删除。采用 imageio.imread 代替。
imageio.imread(uri, format=None, **kwargs)
从指定文件中读取图像。返回一个 numpy 数组,其中 在其“元”属性中带有元数据字典。
请注意,图像数据按原样返回,并且可能并不总是有 uint8 的 dtype(因此可能与 PIL 返回的不同)。
例子:
import matplotlib.pyplot as plt
from imageio import imread
url = "http://matplotlib.sourceforge.net/_static/logo2.png"
img = imread(url)
plt.imshow(img)
【讨论】: