背景
需要将无限制链接转换为本地图片进行后续处理,这里需要用到python的urllib
包,该包收集了多个涉及 URL 的模块的包:
这里需要用到urllib.request
包进行打开和读取图片链接url
详细介绍可以参见:
urllib.request.urlopen
, 打开统一资源定位地址 url,可以是一个字符串或一个 Request 对象。#!/usr/bin/env python
# fileUsing: download img from not restrict url
import os
import cv2
import urllib.request
import numpy as np
class Url2Image(object):
def url_to_image(self, url):
resp = urllib.request.urlopen(url)
image = np.array(bytearray(resp.read()), dtype="uint8") # 转换格式
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
# cv2.imdecode()函数从指定的内存缓存中读取数据,并把数据转换(解码)成图像格式;主要用于从网络传输数据中恢复出图像
# save file and convert into cv2 imread
image_name = url.split('/')[-1]
cv2.imwrite(image_name, image) # save img
image = cv2.imread(image_name)
os.remove(image_name) # remove local img file
return image
if __name__ == '__main__':
u2i = Url2Image()
url = "https://s1.ax1x.com/2020/09/23/wx6jRU.png"
print("downloading %s" % (url))
image = u2i.url_to_image(url)
cv2.imshow("Image", image)
cv2.waitKey(0)