Search code examples
pythonopencvurllib2loadimage

Python: Urllib2 and OpenCV


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?


Solution

  • 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.