如何从 Python cv2、scikit 图像和 mahotas 中的 Internet URL 读取图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21061814/
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
How can I read an image from an Internet URL in Python cv2, scikit image and mahotas?
提问by postgres
How can I read an image from an Internet URL in Python cv2?
如何从 Python cv2 中的 Internet URL 读取图像?
This Stack Overflow answer,
这个堆栈溢出答案,
import cv2.cv as cv
import urllib2
from cStringIO import StringIO
import PIL.Image as pil
url="some_url"
img_file = urllib2.urlopen(url)
im = StringIO(img_file.read())
is not good because Python reported to me:
不好,因为 Python 向我报告:
TypeError: object.__new__(cStringIO.StringI) is not safe, use cStringIO.StringI.__new__
采纳答案by berak
Since a cv2 image is not a string (save a Unicode one, yucc), but a NumPy array, - use cv2 and NumPy to achieve it:
由于 cv2 图像不是字符串(保存一个 Unicode 的 yucc),而是一个 NumPy 数组, - 使用 cv2 和 NumPy 来实现它:
import cv2
import urllib
import numpy as np
req = urllib.urlopen('http://answers.opencv.org/upfiles/logo_2.png')
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
img = cv2.imdecode(arr, -1) # 'Load it as it is'
cv2.imshow('lalala', img)
if cv2.waitKey() & 0xff == 27: quit()
回答by Tony S Yu
The following reads the image directly into a NumPy array:
下面将图像直接读入 NumPy 数组:
from skimage import io
image = io.imread('https://raw2.github.com/scikit-image/scikit-image.github.com/master/_static/img/logo.png')
回答by Kelvin Wang
in python3:
在python3中:
from urllib.request import urlopen
def url_to_image(url, readFlag=cv2.IMREAD_COLOR):
# download the image, convert it to a NumPy array, and then read
# it into OpenCV format
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, readFlag)
# return the image
return image
this is the implementation of url_to_image in imutils, so you can just call
这是 imutils 中 url_to_image 的实现,所以你可以调用
import imutils
imutils.url_to_image(url)

