前言
有时候我们需要读取的图片是网络上的图片,应该怎么操作呢?
这里也是介绍两个常用库的做法,即 opencv 和 PIL 。
这里要读取的网络图片,来自上一篇文章:每日一学:如何用matplotlib展示图片:
链接为:https://mmbiz.qpic.cn/mmbiz_png/COhkzD7Mia5mH0pmJ9hdpSBT7x40CVuaPhcWqyiczL37icQs4JTm5px5dbBTwjof5k9ZcGgrtDwzFuiaW4iaQicGmbIA/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1
![e1239cfcaaee17df89a4fcd24db5fdb4.png](https://i-blog.csdnimg.cn/blog_migrate/32f6b44547fcadacd9d2f1241b715ddd.jpeg)
PIL 读取网络图片
代码如下所示:
# 基于 PIL import requestsfrom PIL import Imagefrom io import BytesIO%matplotlib inlineimport matplotlib.pyplot as pltimg_url = 'https://mmbiz.qpic.cn/mmbiz_png/COhkzD7Mia5mH0pmJ9hdpSBT7x40CVuaPhcWqyiczL37icQs4JTm5px5dbBTwjof5k9ZcGgrtDwzFuiaW4iaQicGmbIA/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1'try: encoded_img = requests.get(img_url).content ori_img = Image.open(BytesIO(encoded_img)) plt.imshow(ori_img)except Exception as e: print(f'download image {img_url} error: {e}')
结果如下所示:
![8d3ff50c980b8d3dd59737032f4e64e7.png](https://i-blog.csdnimg.cn/blog_migrate/98f5b7c9589053382a30361841ee2c1e.jpeg)
Opencv 读取网络图片
代码如下所示:
# opencvimport numpy as npimport cv2import requests%matplotlib inlineimport matplotlib.pyplot as plttry: img_url = 'https://mmbiz.qpic.cn/mmbiz_png/COhkzD7Mia5mH0pmJ9hdpSBT7x40CVuaPhcWqyiczL37icQs4JTm5px5dbBTwjof5k9ZcGgrtDwzFuiaW4iaQicGmbIA/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1' img_data = requests.get(img_url).content img = np.asarray(bytearray(img_data), dtype="uint8") img = cv2.imdecode(img, -1) plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))except Exception as e: print(f'download image {img_url} error: {e}')
结果如下所示:
![443ba59b9fd7c2e3b0722235f8f3d516.png](https://i-blog.csdnimg.cn/blog_migrate/b1ad2ff9d50e90a5a4544df178066273.jpeg)