LoginSignup
26
15

More than 5 years have passed since last update.

pillowモジュールにおいてURLから直接画像を読み込む

Posted at

pillowモジュールのImage.openの引数にはファイル名を渡す使い方が一般的だが、ファイルオブジェクトを渡しても開くことができる。

img = Image.open('localfile.jpg')

リモートのファイルを読み込む方法

ローカルのファイルではなく、リモートのファイルを直接読み込みたい場合、2つの方法がある。

  • リモートのファイルをローカルにダウンロードして読み込む
  • リモートのファイルを直接読み込む

前者は無駄にストレージを使用するため、保存する必要がないときには使いたくない。
リモートへのアクセスが一時的に保証されているなら、後者のほうがローカルストレージを圧迫しないため、手軽。メモリ上に展開されるだけなので、明示的に消さなくても良い。

URLから直接画像を読み込む

requestモジュールと、ioモジュールを使えば簡単にできる。

コア部分

ioモジュール: https://docs.python.jp/3/library/io.html#io.BytesIO
requestsモジュール: http://docs.python-requests.org/en/master/user/quickstart/#binary-response-content


io.BytesIO(requests.get(a_url).content)

コード

import matplotlib.pyplot as plt
from PIL import Image
import requests
import io

a_url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa,_by_Leonardo_da_Vinci,_from_C2RMF_retouched.jpg/687px-Mona_Lisa,_by_Leonardo_da_Vinci,_from_C2RMF_retouched.jpg'
b_url = 'https://pixabay.com/static/uploads/photo/2012/11/28/08/56/mona-lisa-67506_960_720.jpg'

# core
a_img = Image.open(io.BytesIO(requests.get(a_url).content))
b_img = Image.open(io.BytesIO(requests.get(b_url).content))

# images scale up
plt.figure(figsize=(20,20))

# display images horizontally
plt.subplot(121)
plt.imshow(a_img)
plt.subplot(122)
plt.imshow(b_img)

26
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
15