python opencv讀取網路圖片

ShellCollector發表於2019-03-04

pil

方法二,使用PIL+requests:

import requests
from PIL import Image
from io import BytesIO

response = requests.get(img_src)
image = Image.open(BytesIO(response.content))
image.save('D:/9.jpg')

 

 

 


import time

import cv2
import numpy as np
import requests

path='d:/guo.jpg'

# img=cv2.imread(path)
# x = img.tobytes()
# # 從二進位制檔案到圖片(numpy.ndarray):
#
# aaa=np.fromstring(x, np.uint8)
# img = cv2.imdecode(aaa ,cv2.IMREAD_COLOR)
#
# cv2.imshow("1",img)
# cv2.waitKeyEx()
# import cv2   # opencv-python (3.4.2.16)
# import numpy as np  # numpy (1.14.5)


#每一張圖片需要600ms
for i in range(10):
    start=time.time()
    file = requests.get("https://www.baidu.com/img/bd_logo1.png")
    img = cv2.imdecode(np.fromstring(file.content, np.uint8), 1)    #file.content 是讀取的遠端檔案的位元組流
    print('time',time.time()-start)
cv2.imshow("1",img)
cv2.waitKeyEx()


#需要1000ms左右
for i in range(10):
    start=time.time()
    # file = requests.get("https://www.baidu.com/img/bd_logo1.png")
    url = 'http://i5.qhimg.com/t019c3e49c9c9319c33.jpg'
    url = 'https://www.baidu.com/img/bd_logo1.png'
    cap = cv2.VideoCapture(url)
    ret = cap.isOpened()
    while (ret):
        ret, img = cap.read()
        if not ret: break
    # img = cv2.imdecode(np.fromstring(file.content, np.uint8), 1)    #file.content 是讀取的遠端檔案的位元組流
    print('time',time.time()-start)
cv2.imshow('photo', img)
cv2.waitKey(0)

 

相關文章