Python 能够非常方便的进行计算机视觉方向的人工智能编程。利用 Python 可以轻易的处理图片,这主要归功于图像/视频处理相关库或包,如 OpenCV, Pillow, imagio, PyTorch, TensorFlow, matplotlib等。本篇介绍,如何利用 Python 在线加载网络图片,方便后续的图片处理,模型训练等。所有代码以 Jupyter notebook 为运行环境。
假设网络上的图片 url 如下:
1
| url = "https://p1-tt.byteimg.com/origin/pgc-image/fe41801208fa40d394352e0df71e9202?from=pc"
|
方法1
1 2 3 4 5 6
| from urllib import request
from PIL import Image
img = Image.open(request.urlopen(url)) img
|
方法2
1 2 3 4 5 6
| import requests from PIL import Image
response = requests.get(url, stream=True) img = Image.open(response.raw).convert("RGB") img
|
1 2 3 4 5
| import numpy as np import cv2
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
|
方法3
1 2 3 4 5 6 7 8
| from io import BytesIO
import requests from PIL import Image
response = requests.get(url) img = Image.open(BytesIO(response.content)) img
|
方法4
1 2 3 4 5 6 7 8
| from io import BytesIO
import matplotlib.pyplot as plt import requests
response = requests.get(url) img = plt.imread(BytesIO(response.content), format="JPG") plt.imshow(img)
|
方法5
1 2 3 4 5 6 7 8
| import matplotlib.pyplot as plt from imageio import imread
img = imread(url) plt.imshow(img) plt.show()
|
以上五种方法都能够获取到图片数据,并展示出来。