Python: Urllib2 and OpenCV

老子叫甜甜 提交于 2019-12-10 14:32:49

问题


I have a program that saves an image in a local directory and then reads the image from that directory.

But I dont want to save the image. I want to read it directly from the url.

Here's my code:

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)

If i change it to:

img = cv.LoadImage(img)

This will give me this error:

argument 1 must be string without null bytes, not str

What can I do?


回答1:


If you want you can use 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)

I guess by this method you don't need to save the image file.




回答2:


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



回答3:


As mentioned here LoadImage expecting filename as first argument, not data



来源:https://stackoverflow.com/questions/11253820/python-urllib2-and-opencv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!