5

我有一个程序将图像保存在本地目录中,然后从该目录中读取图像。

但我不想保存图像。我想直接从 url 读取它。

这是我的代码:

import cv2.cv as cv
import urllib2

url = "http://cache2.allpostersimages.com/p/LRG/18/1847/M5G8D00Z/posters/curious-cat.jpg"
filename = "my_test_image" + url[-4:]
print filename
opener = urllib2.build_opener()

page = opener.open(url) 
img= page.read()

abc = open(filename, "wb")
abc.write(img)
abc.close()

img = cv.LoadImage(filename)

cv.ShowImage("Optical Flow", img)
cv.WaitKey(30)

如果我将其更改为:

img = cv.LoadImage(img)

这会给我这个错误:

参数 1 必须是没有空字节的字符串,而不是 str

我能做些什么?

4

3 回答 3

4

如果你愿意,你可以使用 PIL。

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())
source = pil.open(im).convert("RGB")
bitmap = cv.CreateImageHeader(source.size, cv.IPL_DEPTH_8U, 3)
cv.SetData(bitmap, source.tostring())
cv.CvtColor(bitmap, bitmap, cv.CV_RGB2BGR)

我想通过这种方法你不需要保存图像文件。

于 2012-06-29T11:06:48.820 回答
0
import numpy as np
import urllib
import cv2

def url_to_image(url):
    response = urllib.urlopen(url)
    image = np.asarray(bytearray(response.read()), dtype="uint8")
    cv2_img = cv2.imdecode(image, cv2.IMREAD_COLOR)
    return cv2_img
于 2019-05-26T07:11:12.110 回答
-1

如此处所述LoadImage 期望文件名作为第一个参数,而不是数据

于 2012-06-29T05:58:01.923 回答