2
1

More than 1 year has passed since last update.

画像をURLからダウンロードして、gzipで圧縮し、base85でエンコードして軽量化したのち、復元してnp.arraybufferで読み込んで表示

Posted at

画像をPythonオブジェクトとして保持しておきたい場面があったので、メモ書きです。

画像の読み込み

  • 必要なパッケージのインポート
import requests
from PIL import Image
import numpy as np
from io import BytesIO
import matplotlib.pyplot as plt
import gzip
import base64
  • 画像をダウンロードして表示
url = "http://placekitten.com/600/400"

res = requests.get(url)
img = Image.open(BytesIO(res.content))

plt.imshow(img)

image.png

変換、圧縮

  • ndarrayに変換
array = np.array(img)
array.shape
# (400, 600, 3)
  • gzipで圧縮
compressed = gzip.compress(array.tobytes())
compressed
# b'\x1f\x8b\x08\x00\xbc%\xbdd\x02\xff\xec\xbd\xe7w#\xd7\x99\xee\xfb\xfd\x9e\x99\xf18\xc9\n...'
  • base85でエンコード
encoded = base64.b85encode(compressed)
encoded
# b'ABzY8yd}M40{`s2=XWF5neO}jo|*AD$qKC;EeBbl)tMa`n>m046PN=)f?...'

デコード

  • デコード・解凍・読み込み
img_array = np.frombuffer(gzip.decompress(base64.b85decode(encoded)), dtype=np.uint8)
img_array.shape
# (720000,)
  • 1次元で読み込まれてしまうので、変換
img_array = img_array.reshape(400, 600, 3)
img_array.shape

表示

plt.imshow(img_array)

image.png

2
1
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
2
1