Loading [MathJax]/extensions/tex2jax.js

[matplotlib animation] 51. 画像の拡大アニメーション

matplotlib Animation

はじめに

ここでは、matplotlib FuncAnimationによって画像を拡大するアニメーションについて解説する。

コード

%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
image = plt.imread('shi2oumaru.jpg')
s=image.shape[0]
fig, ax = plt.subplots(figsize=(6,6))
ax.imshow(image)
ax.axis('off')
def update(num):
ax.set_xlim(num, s-num)
ax.set_ylim(num, s-num)
ani = animation.FuncAnimation(fig, update, 1000, interval=10)
#HTML(ani.to_html5_video())
ani.save('zoomanim.mp4', writer="ffmpeg",dpi=100)
view raw zoomupanim.py hosted with ❤ by GitHub

解説

モジュールのインポート

%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
view raw zoomupanim.py hosted with ❤ by GitHub

画像の読み込み

image = plt.imread('shi2oumaru.jpg')
s=image.shape[0]
view raw zoomupanim.py hosted with ❤ by GitHub

鶴仙園で購入したパロディア属 獅子王丸を用いる。
sはイメージの横のサイズとなる。ここではs=2020となっている。
一辺のサイズが2020もある画像だとファイルサイズが1 MB程度となってしまい、貧弱な環境ではアニメーションを作成するのに時間がかかる。そこで下記サイトでファイルサイズの圧縮した。

Squoosh
Squoosh is the ultimate image optimizer that allows you to compress and compare images with different codecs in your bro...

web上で動作するのでchromebookなどでも使用可能となっている。これにより、1 MBを374 KBにすることができた。

画像の表示

fig, ax = plt.subplots(figsize=(6,6))
ax.imshow(image)
ax.axis('off')
view raw zoomupanim.py hosted with ❤ by GitHub

アニメーション設定

def update(num):
ax.set_xlim(num, s-num)
ax.set_ylim(num, s-num)
view raw zoomupanim.py hosted with ❤ by GitHub

set_xlim()とset_ylim()により表示範囲を狭めて画像を拡大する。

アニメーションの表示

ani = animation.FuncAnimation(fig, update, 1000, interval=10)
#HTML(ani.to_html5_video())
ani.save('zoomanim.mp4', writer="ffmpeg",dpi=100)
view raw zoomupanim.py hosted with ❤ by GitHub

1000stepアニメーション関数を実行して、10 ms間隔で順次表示していくので、10 secのアニメーションとなる。
HTML(ani.to_html5_video())とすればjupyter notebook上にアニメーションを表示できる。

コードをダウンロード(.pyファイル)

コードをダウンロード(.ipynbファイル)

参考

ホーム | 鶴仙園
90年に渡り培ったノウハウを活かし世界中のサボテン、多肉植物、交配種など幅広く様々な品種を取り扱っています。お客様へ常に新しい出会いと驚きを提供できるように力を注いでいます。

コメント