39

如何在 Python cv2 中从 Internet URL 读取图像?

这个堆栈溢出答案

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__
4

5 回答 5

48

由于 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()
于 2014-01-11T12:07:59.040 回答
38

下面将图像直接读入 NumPy 数组:

from skimage import io

image = io.imread('https://raw2.github.com/scikit-image/scikit-image.github.com/master/_static/img/logo.png')
于 2014-01-11T15:36:55.347 回答
16

在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)
于 2019-03-06T15:42:50.480 回答
0

如果您正在使用请求,则可以使用此

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)
于 2021-05-06T09:24:50.110 回答
0

使用请求:

def url_to_numpy(url):                     
  img = Image.open(BytesIO(requests.get(url).content))                                 
  return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
于 2022-01-29T04:26:19.350 回答