This article mainly describes the python through the URL to open a picture instance of the relevant information, the need for friends can refer to the following
Python opens a picture instance by URL
Whether using OpenCV or pil,skimage, in the previous image processing, almost all of the images are read locally. Recently try to crawl the image, before saving, I would like to be able to quickly browse through the picture, and then have a selective save. Here you need to read the image from the URL. Looked up a lot of information, found that there are several methods, here to make a record.
The image URLs used in this article are as follows:
IMG_SRC = ' http://wx2.sinaimg.cn/mw690/ac38503ely1fesz8m0ov6j20qo140dix.jpg '
1. Use OpenCV
OpenCV's Imread () can only load local images, and cannot load images via URLs. However, OpenCV's Videocapture class can load video from a URL. If we only use OPENCV, we can have a roundabout way: first load the image under the URL with Videocapure, and then pass it on to Mat.
Import Cv2cap = Cv2. Videocapture (IMG_SRC) if (cap.isopened ()): ret,img = Cap.read () cv2.imshow ("image", img) Cv2.waitkey ()
2. Opencv+numpy+urllib
Import NumPy as Npimport urllibimport cv2resp = Urllib.urlopen (img_src) image = Np.asarray (ByteArray ()), Resp.read "Uint8") image = Cv2.imdecode (image, Cv2. Imread_color) cv2.imshow ("image", image) Cv2.waitkey (0)
Urlopen returns a class file object that provides the following methods:
Read (), ReadLine (), ReadLines (), Fileno (), Close (): These methods are used in exactly the same way as file objects. The returned class file object is then re-encoded and converted to a picture to be passed to mat.
3.pil+requests
Import requests as Reqfrom PIL import imagefrom io import bytesioresponse = Req.get (img_src) image = Image.open (Bytesio (res ponse.content)) Image.show ()
The requests can access the request response body in bytes, which is the code that creates a picture of the binary data returned by the request.
4. Skimage
From skimage Import ioimage = Io.imread (IMG_SRC) io.imshow (image) Io.show ()
Relatively speaking, this approach should be the simplest, because skimage can directly use the Imread () function to read Web page pictures, without the need for additional assistance, and do not need to detour.