Loading [MathJax]/extensions/tex2jax.js

[scikit-image] 73. サイズの異なる正方形の構造化要素を生成(skimage.morphology.square)

matplotlib

はじめに

skimage.morphologyのsquareで、様々なサイズの正方形構造化要素を作成して表示する。

コード

#square
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from skimage.morphology import square
# Generate 2D structuring square elements.
struc_2d = {
"square(1)": square(1),
"square(2)": square(2),
"square(3)": square(3),
"square(4)": square(4),
"square(5)": square(5),
"square(6)": square(6)}
# Visualize the elements.
fig = plt.figure(figsize=(8,5))
idx = 1
for title, struc in struc_2d.items():
ax = fig.add_subplot(2, 3, idx)
ax.imshow(struc, cmap="summer", vmin=0, vmax=2,zorder=2)
for i in range(struc.shape[0]):
for j in range(struc.shape[1]):
ax.text(j, i, struc[i, j], ha="center", va="center", color="k",zorder=3)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
ax.grid()
ax.set(xlim=(-1,struc.shape[0]),ylim=(-1,struc.shape[0]))
ax.set_title(title)
ax.set_axisbelow(True)
idx += 1
fig.tight_layout()
plt.savefig('square.png',dpi=100)
plt.show()

解説

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

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from skimage.morphology import square

バージョン

#version
import skimage
print(skimage.__version__)
#0.16.2
import matplotlib
print(matplotlib.__version__)
#3.2.0
print(np.__version__)
#1.18.1

構造化要素の生成

struc_2d = {
"square(1)": square(1),
"square(2)": square(2),
"square(3)": square(3),
"square(4)": square(4),
"square(5)": square(5),
"square(6)": square(6)}

辞書形式でwidth(height)が1から6のsquareを作成する。

構造化要素の表示

fig = plt.figure(figsize=(8,5))
idx = 1
for title, struc in struc_2d.items():
ax = fig.add_subplot(2, 3, idx)
ax.imshow(struc, cmap="summer", vmin=0, vmax=2,zorder=2)
for i in range(struc.shape[0]):
for j in range(struc.shape[1]):
ax.text(j, i, struc[i, j], ha="center", va="center", color="k",zorder=3)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
ax.grid()
ax.set(xlim=(-1,struc.shape[0]),ylim=(-1,struc.shape[0]))
ax.set_title(title)
ax.set_axisbelow(True)
idx += 1
fig.tight_layout()
plt.savefig('square.png',dpi=100)
plt.show()

plt.figure(figsize=(8,5))でfigを作成し、fig.add_subplot(2, 3, idx)で図を順次生成していく。ax.imshow(struc)で構造化要素を表示する。
2重のfor文とax.textにより各ピクセルの中央に各ピクセルの値を表示する。
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))とすることで1ごとに目盛りを表示する。
この状態でax.grid()をすると、1ごとにグリッドが表示されることになる。
ax.set(xlim=(-1,struc.shape[0]),ylim=(-1,struc.shape[0]))で各構造化要素の大きさに応じた軸範囲設定を行う。
ax.set_axisbelow(True)によりグリッドを再下面に表示する。
idx += 1によりidxに1を足して次の図の作成を行う。

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

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

参考

Generate footprints (structuring elements) — skimage 0.25.2rc0.dev0 documentation
skimage.morphology — skimage 0.25.2rc0.dev0 documentation

コメント