LoginSignup
1
1

More than 1 year has passed since last update.

GoogleColabでweb上のGIFを画像に分解して保存

Posted at

コード

GoogleColabのVM内に画像を保存する関係で、大きいサイズのファイルを扱うのは避ける。
また、インスタンスが切れてしまえば保存したデータは全てリセットされる。

画像を保存するディレクトリをVM上に作成

import os
path_content = '/content/img/' #VM上のディレクトリを指定
if not os.path.exists(path_content):
    os.mkdir(path_content)

Googleの画像検索などで画像を開いたときに、"画像アドレスをコピー"したものをurlに入れる。

import requests
from PIL import Image, ImageSequence
import io
import numpy as np
url = "" #保存したい画像の画像アドレス
fname_img = "img" #保存したい画像のファイル名
fname_imgext = "png" #保存したい画像の拡張子

response = requests.get(url)
image = response.content
img = Image.open(io.BytesIO(image))
for idx, frame in enumerate(ImageSequence.Iterator(img)):
    fname = "{}{}-{}.{}".format(path_content, fname_img, idx, fname_imgext)
    frame.save(fname)

画像アドレスに対して、requestを使ったGETリクエストを送信。
GETリクエストに対するレスポンスボディをバイナリ形式で取得して、io.BytesIO()でBytesオブジェクトにすれば、Image.open()で画像データを開ける。

もちろんGIFだけでなく画像ならこの方法でいけた。

おわりに

勉強した内容やふと思いついた内容を試すときに、いちいちマイドライブから読み出すのは認証する手間もあって面倒だった。
というわけで、web上のデータをダウンロードして保存する処理の方がコピペして使いまわせるし、自分的に楽なのではと思ったのが始まり。

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