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

[scikit-image] 48. rag_boundary(skimage.future graph)で領域境界グラフ(RAG)を構築

python

はじめに

skimage.future graphのrag_boundaryにより、エッジ画像から領域境界RAGを構築する例について説明する。

コード

from skimage.future import graph
from skimage import segmentation, color, filters
from matplotlib import pyplot as plt
img = plt.imread('zou.jpg')
gimg = color.rgb2gray(img)
labels = segmentation.slic(img, compactness=30, n_segments=400)
edges = filters.sobel(gimg)
edges_rgb = color.gray2rgb(edges)
g = graph.rag_boundary(labels, edges)
lc = graph.show_rag(labels, g, edges_rgb, img_cmap=None, edge_cmap='cividis',
edge_width=1.2)
plt.colorbar(lc, fraction=0.03)
plt.savefig('RBbasedRAGs.jpg',dpi=130)
plt.show()
view raw rbb_rags.py hosted with ❤ by GitHub

解説

モジュールのインポート

from skimage.future import graph
from skimage import segmentation, color, filters
from matplotlib import pyplot as plt
view raw rbb_rags.py hosted with ❤ by GitHub

画像データの読み込み

img = plt.imread('zou.jpg')
gimg = color.rgb2gray(img)
view raw rbb_rags.py hosted with ❤ by GitHub

コリファンタ属の象牙丸を用いる。rgb2grayによりグレースケール画像とする。

k平均法によるセグメント化

labels = segmentation.slic(img, compactness=30, n_segments=400)
view raw rbb_rags.py hosted with ❤ by GitHub

segmentation.slic()により、k平均法によるセグメント化を行う。
imgはセグメント化する画像で、
compactnessは色の近接性と空間の近接性のバランスのパラメータであり、値を大きくするとスペースの近接度が高くなりセグメント化された形状が正方形に近い形となる。値の調整は、ログスケール(0.01から100)で行うことが推奨されている。
n_segmentsは概算のセグメント数となり、多くするほどより細かくセグメント化される。

エッジ画像の生成

edges = filters.sobel(gimg)
edges_rgb = color.gray2rgb(edges)
view raw rbb_rags.py hosted with ❤ by GitHub

グレースケール画像からエッジ画像を生成する。sobelフィルタについては下記で説明した。

[scikit-image] 16. エッジ演算子(filters.roberts, sobel)
skimage.filters の roberts, sobelを用いた画像のエッジ検出について説明する。

edges_rgb = color.gray2rgb(edges)により1次元のグレースケール画像を3次元のRGB画像とする。

領域境界にもとづくRAG

g = graph.rag_boundary(labels, edges)
view raw rbb_rags.py hosted with ❤ by GitHub

graph.rag_boundary(labels, edges)で、セグメント化された画像とエッジ画像から、領域隣接グラフ(RAG)を構築する。2つの隣接する領域間の境界に沿ったピクセルの重みは、edge_mapの対応する領域の平均値となる。

領域隣接グラフを表示

lc = graph.show_rag(labels, g, edges_rgb, img_cmap=None, edge_cmap='cividis',
edge_width=1.2)
view raw rbb_rags.py hosted with ❤ by GitHub

ラベル画像とRAGから、指定されたカラーマップでRAGのノード、エッジを表示する。
edges_rgbのように入力画像はRGB画像にする必要がある。edge_cmapでエッジに用いるカラーマップ、edge_widthで線の太さを調整できる。

コードをダウンロード

参考

Region Boundary based Region adjacency graphs (RAGs) — skimage 0.25.2 documentation
skimage.segmentation — skimage 0.25.2 documentation
Page not found · GitHub Pages
Page not found · GitHub Pages
skimage.filters — skimage 0.25.2 documentation

コメント