Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read an image from an Internet URL in Python cv2, scikit image and mahotas?

How can I read an image from an Internet URL in Python cv2?

This Stack Overflow answer,

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()) 

is not good because Python reported to me:

TypeError: object.__new__(cStringIO.StringI) is not safe, use cStringIO.StringI.__new__ 
like image 798
postgres Avatar asked Jan 11 '14 11:01

postgres


People also ask

How do you read a cv2 image?

The first Command line argument is the image image = cv2. imread(sys. argv[1]) #The function to read from an image into OpenCv is imread() #imshow() is the function that displays the image on the screen. #The first value is the title of the window, the second is the image file we have previously read.


2 Answers

Since a cv2 image is not a string (save a Unicode one, yucc), but a NumPy array, - use cv2 and NumPy to achieve it:

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() 
like image 153
berak Avatar answered Sep 29 '22 03:09

berak


The following reads the image directly into a NumPy array:

from skimage import io  image = io.imread('https://raw2.github.com/scikit-image/scikit-image.github.com/master/_static/img/logo.png') 
like image 44
Tony S Yu Avatar answered Sep 29 '22 03:09

Tony S Yu