我有很多存盤在網路上的影像 URL,URL 示例如下:
https://m.media-amazon.com/images/M/MV5BOWE4M2UwNWEtODFjOS00M2JiLTlhOGQtNTljZjI5ZTZlM2MzXkEyXkFqcGdeQXVyNjUwNzk3NDc@._V1_QL75_0UX190
我想從上面提到的類似 URL 加載影像,然后對該影像執行一些操作,然后回傳結果影像。
所以這是我的代碼:
def get_image_from_url(url, path):
try:
# downloading image from url
img = requests.get(url)
with open(path, 'wb') as f:
f.write(img.content)
# reading image, str(path) since path is object of Pathlib's path class
img = cv2.imread(str(path), cv2.IMREAD_COLOR)
# some operations
# deleting that downloaded image since it is of no use now
if os.path.exists(path):
os.remove(path)
return resulting_image
except Exception as e:
return np.zeros((224, 224, 3), np.uint8)
但是這個程序花費了太多時間,所以我想不是下載和洗掉影像,而是直接將 URL 上的影像加載到變數中。
像這樣的事情:
def store_image_from_url(url):
image = get_image_from_url(url) # without downloading it into my computer
# do some operations
return resulting_image
有沒有辦法做同樣的事情?
謝謝
uj5u.com熱心網友回復:
作為如何從 Python cv2、scikit 影像和 mahotas 中的 Internet URL 讀取影像?,它可以是這樣的:
import cv2
import urllib
import numpy as np
def get_image_from_url(url):
req = urllib.urlopen(url)
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
img = cv2.imdecode(arr, -1)
return img
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/387994.html
上一篇:檢查多列并從其他多列回傳到單元格
下一篇:如何錨定文本并將其縮小以適合影像
