如何绘制远程图像(来自http url)

the*_*eta 8 matplotlib

这一定很简单,但我现在不知道如何在不使用urllib模块和手动获取远程文件的情况下

我想用远程图像叠加图(让我们说"http://matplotlib.sourceforge.net/_static/logo2.png"),既不imshow()imread()不能加载图像.

任何功能的想法将允许加载远程图像?

cro*_*wdy 15

你可以用这段代码做到这一点;

from matplotlib import pyplot as plt
a = plt.imread("http://matplotlib.sourceforge.net/_static/logo2.png")
plt.imshow(a)
plt.show()
Run Code Online (Sandbox Code Playgroud)

  • 您建议如何处理 403 错误? (2认同)

Dan*_*kov 13

这很容易:

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()
Run Code Online (Sandbox Code Playgroud)

  • 对于python 3,导入`urllib`而不是`urllib2`并调用`urllib.request.urlopen`而不是`urllib2.urlopen`. (4认同)
  • 另外,imread无法从这样的流中猜出文件类型.它默认为PNG,因此仅适用于PNG.对于非PNG文件,需要将format参数传递给imread(例如format ='jpg').这需要额外的工作来从URL中提取文件类型. (2认同)

Jul*_*ian 8

这适用于我在python 3.5的笔记本中:

from skimage import io
import matplotlib.pyplot as plt

image = io.imread(url)
plt.imshow(image)
plt.show()
Run Code Online (Sandbox Code Playgroud)

  • 我为`urllib2`解决方案得到了'ValueError:无效的PNG标题`,但这对我来说效果很好 (3认同)
  • 要获取 skimage,“pip install scikit-image” (2认同)