Python opens picture instance detail with URL

  • 2020-06-03 06:59:33
  • OfStack

Python opens picture instance detail with URL

Whether using OpenCV or PIL, skimage and other libraries, when doing image processing before, it is almost always to read the local image. Recently, I have tried to crawl to get pictures. Before saving, I hope to browse through the pictures quickly and then save them selectively. Here you need to read the images from url. I looked up a lot of information and found that there are several ways, here is a record.

The picture URL used in this paper is as follows:

img_src = 'http://wx2.sinaimg.cn/mw690/ac38503ely1fesz8m0ov6j20qo140dix.jpg'

1. Use OpenCV

imread() of OpenCV can only load local images, not images via the url. However, the VideoCapture class of opencv can load videos from url. If we only use opencv, we can use a roundabout way: first load the image under the url with VideoCapure, and then send it to Mat.


import cv2
cap = cv2.VideoCapture(img_src)
if( cap.isOpened() ) :
  ret,img = cap.read()
  cv2.imshow("image",img)
  cv2.waitKey()

2. OpenCV+Numpy+urllib


import numpy as np
import urllib
import cv2
resp = urllib.urlopen(img_src)
image = np.asarray(bytearray(resp.read()), dtype="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 exactly the same way as file objects. The returned class file object is then recoded into an image and sent to Mat.

3.PIL+requests


import requests as req
from PIL import Image
from io import BytesIO
response = req.get(img_src)
image = Image.open(BytesIO(response.content))
image.show()

requests can access the body of the request response in bytes. This is the code to create an image based on the binary data returned by the request.

4. skimage


from skimage import io
image = io.imread(img_src)
io.imshow(image)
io.show()

This approach should be relatively simple, as skimage can read web page images directly as the imread() function without any additional assistance or detour.

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: