5

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?

Kevin Bedell
  • 13,254
  • 10
  • 78
  • 114
reiver
  • 117
  • 1
  • 8

3 Answers3

4

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.

Froyo
  • 17,947
  • 8
  • 45
  • 73
  • Thanks for this, very useful! One point: I got an error with "from CStringIO...". It should be "from cStringIO..." (lowercase 'c'). – Phil Gyford Jul 09 '12 at 12:40
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
techkuz
  • 3,608
  • 5
  • 34
  • 62
-1

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

couchemar
  • 1,927
  • 19
  • 22