Loading [MathJax]/jax/output/HTML-CSS/config.js

[ipywidgets] 26. IntRangeSliderで画像の任意の位置に四角を表示

ipywidgets

はじめに

jupyter notebookの対話的にパラメータを調整できる機能(ipywidgets IntRangeSlider)で、画像の任意の位置に四角をインタラクティブに表示する方法について説明する。

コード

%matplotlib widget
from ipywidgets import IntRangeSlider,interactive
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
from ipywidgets import HBox
from matplotlib.patches import Rectangle
from mpl_toolkits.axes_grid1 import make_axes_locatable
plt.rcParams['font.size']=12
plt.rcParams['font.family'] = 'sans-serif'
#make data
n = 3
s = 128
im = np.zeros((s, s))
points = (s*np.random.random((2, n**2))).astype(int)
im[points[0], points[1]] = 1000
points = (s*np.random.random((2, n**2))).astype(int)
im[points[0], points[1]] = -1000
im = ndimage.gaussian_filter(im, sigma=s/(5.*n))
fig, ax = plt.subplots(figsize=(5,5))
ax.imshow(im, cmap=plt.cm.gist_earth, interpolation='gaussian',origin='lower')
x_range = IntRangeSlider(min=0, max=127,step=1,value=[0,128], description="xlim: ",
orientation='horizontal')
y_range = IntRangeSlider(min=0, max=127,step=1,value=[0,128], description="ylim: ",
orientation='vertical')
rects = Rectangle((0, 0),0,0,ls=":",lw=2,ec="w",fc="None")
ax.add_patch(rects)
def plot(x_range,y_range):
rects.set_xy([x_range[0],y_range[0]])
rects.set_width(x_range[1]-x_range[0])
rects.set_height(y_range[1]-y_range[0])
w = interactive(plot, x_range=x_range, y_range=y_range)
HBox(children=[y_range,x_range])
view raw ipy_rect.py hosted with ❤ by GitHub

解説

モジュールのインポートなど

%matplotlib widget
from ipywidgets import IntRangeSlider,interactive
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
from ipywidgets import HBox
from matplotlib.patches import Rectangle
from mpl_toolkits.axes_grid1 import make_axes_locatable
view raw ipy_rect.py hosted with ❤ by GitHub

バージョン

import matplotlib
print(matplotlib.__version__)
3.2.1
print(np.__version__)
1.18.5
import scipy
print(scipy.__version__)
1.4.1
import ipywidgets
print(ipywidgets.__version__)
7.5.1
view raw ipy_rect.py hosted with ❤ by GitHub

データの生成

#make data
n = 3
s = 128
im = np.zeros((s, s))
points = (s*np.random.random((2, n**2))).astype(int)
im[points[0], points[1]] = 1000
points = (s*np.random.random((2, n**2))).astype(int)
im[points[0], points[1]] = -1000
im = ndimage.gaussian_filter(im, sigma=s/(5.*n))
view raw ipy_rect.py hosted with ❤ by GitHub

画像データは下記記事と同じコードにより生成した。

[matplotlib] 57. plt.imshow()で軸を画像から離して表示
matplotlibのplt.imshowで画像を表示する際に、軸を画像から離して表示する方法について説明する。

画像の表示

fig, ax = plt.subplots(figsize=(5,5))
ax.imshow(im, cmap=plt.cm.gist_earth, interpolation='gaussian',origin='lower')
view raw ipy_rect.py hosted with ❤ by GitHub

四角の表示

rects = Rectangle((0, 0),0,0,ls=":",lw=2,ec="w",fc="None")
ax.add_patch(rects)
view raw ipy_rect.py hosted with ❤ by GitHub

左下の座標が(0, 0)で幅0、高さ0のRectangleを作成し、ax.add_patch(rects)で図中に入れておく。

ipywidgetsの設定

IntRangeSliderの設定

x_range = IntRangeSlider(min=0, max=127,step=1,value=[0,128], description="xlim: ",
orientation='horizontal')
y_range = IntRangeSlider(min=0, max=127,step=1,value=[0,128], description="ylim: ",
orientation='vertical')
view raw ipy_rect.py hosted with ❤ by GitHub

IntRangeSliderで整数で範囲を指定できる。minは最小値で, maxは最大値、stepは刻み幅でvalueは初期値となる。 descriptionでスライダーの前にラベルをつけることができ、orientation=’horizontal’で水平方向、’vertical’で垂直方向にスライダーを設置するこことができる。

def plot(x_range,y_range):
rects.set_xy([x_range[0],y_range[0]])
rects.set_width(x_range[1]-x_range[0])
rects.set_height(y_range[1]-y_range[0])
view raw ipy_rect.py hosted with ❤ by GitHub

x_lim、y_limのスライダーで選択した範囲に四角が表示されるように、四角の左下位置をset_xyで設定し、幅をset_width、高さをset_heightで設定する。

IntRangeSliderの表示

w = interactive(plot, x_range=x_range, y_range=y_range)
HBox(children=[y_range,x_range])
view raw ipy_rect.py hosted with ❤ by GitHub

iinteractではなく、interactiveを用いる。
intaractiveとすることでHBox(children=[y_range,x_range])などのようにipywidgrtsのレイアウト変更が可能となる。
Hboxで横方向にwidgetsが並ぶことになる。

x_lim、y_limを変化させたときの画像の変化

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

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

参考

Using Interact — Jupyter Widgets 8.1.5 documentation
https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20List.html

コメント