如何在Python的cv2、scikit image和mahotas中从互联网URL读取图像?

56

如何在Python cv2中从互联网URL读取图像?

这个Stack Overflow回答

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())

不好,因为Python向我报告了:

TypeError: object.__new__(cStringIO.StringI) is not safe, use cStringIO.StringI.__new__
8个回答

61

由于cv2图像不是字符串(除非是Unicode字符串),而是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()

2
好的,它可以工作,但之后,我还使用了scikit图像库:imgbnbin = mh.morph.dilate(gray, disk7),然后我得到了这个错误:ValueError: morph.get_structuring_elem:Bc没有正确数量的维度。当我使用本地图像时,我不会遇到这个错误,为什么现在会出现? - postgres
也许,我认为通过“url版本”生成了一个3D的numpy数组,而我需要一个2D的numpy数组! - postgres
2
这是一个3D数组,因为它涉及到颜色通道。如果你想要将其转换为2D数组(灰度图像),请使用以下代码:cv2.imdecode(arr,0) # 以灰度图像加载 - berak
25
在Python 3中,urllib.urlopen无法使用,报错为urllib没有名为urlopen的方法。正确方式应该是urllib.request.urlopen() - Puspam
1
对于 Python3,您需要这样打开URL:import urllib.request req = urllib.request.urlopen(url) - sanster9292
显示剩余4条评论

49

以下代码会将图像读取为一个NumPy数组:

from skimage import io

image = io.imread('https://raw2.github.com/scikit-image/scikit-image.github.com/master/_static/img/logo.png')

20

在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

这是imutils中url_to_image的实现,因此您只需调用即可

import imutils
imutils.url_to_image(url)

1
readFlag=cv2.IMREAD_COLOR是在尝试比较相同的远程和本地图像时必不可少的。使用-1会导致图像形状不同。非常感谢! - LaintalAy

1

更新的答案

import urllib
import cv2 as cv2
import numpy as np

url = "https://pyimagesearch.com/wp-content/uploads/2015/01/opencv_logo.png"
url_response = urllib.request.urlopen(url)
img_array = np.array(bytearray(url_response.read()), dtype=np.uint8)
img = cv2.imdecode(img_array, -1)
cv2.imshow('URL Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

我需要将 import urllib 替换为 import urllib.request - usr0192

1
如果您正在使用requests,可以使用以下内容。
import requests
import numpy as np
from io import BytesIO
from PIL import Image

def url_to_img(url, save_as=''):
  img = Image.open(BytesIO(requests.get(url).content))
  if save_as:
    img.save(save_as)
  return np.array(img)

img = url_to_img('https://xxxxxxxxxxxxxxxxxx')
img = url_to_img('https://xxxxxxxxxxxxxxxxxx', 'sample.jpg')

cv2.imshow(img)

1

针对Python 3:

import cv2
from urllib.request import urlopen

image_url = "IMAGE-URL-GOES-HERE"
resp = urlopen(image_url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR) # The image object

# Optional: For testing & viewing the image
cv2.imshow('image',image)

针对使用 Google Colab 的 Python 3:

import cv2
from google.colab.patches import cv2_imshow
from urllib.request import urlopen

image_url = "IMAGE-URL-GOES-HERE"
resp = urlopen(image_url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR) # The image object

# Optional: For testing & viewing the image
cv2_imshow(image)

1

我使用了 @berak 的代码作为基础。如果你有一个需要身份验证(用户名和密码)的URL,你可以使用这种方法:

import cv2
import numpy as np
import requests


resp = requests.get('http://1.2.3.4/media/cam0/still.jpg?res=max',auth = requests.auth.HTTPDigestAuth("my_username","my_password"))
arr = np.asarray(bytearray(resp.content), dtype=np.uint8)
img = cv2.imdecode(arr, -1)

cv2.imshow('lalala', img)
if cv2.waitKey() & 0xff == 27: quit()

0

使用 requests 库:

def url_to_numpy(url):                     
  img = Image.open(BytesIO(requests.get(url).content))                                 
  return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接