C#で細線化 AForge.NET

C#で画像の細線化処理を行って線画像を作成する.コンピュータビジョン等のライブラリであるAForge.NET Frameworkには,モルフォロジー処理が実装されているのでそれを利用する.

細線化のアルゴリズムは以下のサイトあたりを参照.
パターン認識の前処理に必要な二値画像の細線化:CodeZine
細線化アルゴリズム 画像処理ソリューション
technotype

AForge.NETのインストール

Nuget経由でインストール可能.プロジェクトを右クリックして「NuGetパッケージの管理」を選択する.オンラインから「AForge」で検索.「AForge.Imaging」を選択してインストール.

ソースコード

ヒット・ミス演算を行うHitAndMissクラスを使う.

// using AForge.Imaging.Filters; をソースコードに書いておく

// 元画像の読み込み
var bmp = new Bitmap(@"moji.png");
pictureBox1.Image = bmp;

// 二値化処理
var gray = new Grayscale(0.2125,0.7154,0.0721).Apply(bmp);
var binary = new Threshold().Apply(gray);
pictureBox2.Image = binary;            
            
// 細線化用の8つのフィルタを作成
var filterSequence = new FiltersSequence();
filterSequence.Add(new HitAndMiss(
    new short[,] { { 0, 0, 0 }, { -1, 1, -1 }, { 1, 1, 1 } },
    HitAndMiss.Modes.Thinning));
filterSequence.Add(new HitAndMiss(
    new short[,] { { -1, 0, 0 }, { 1, 1, 0 }, { -1, 1, -1 } },
    HitAndMiss.Modes.Thinning));
filterSequence.Add(new HitAndMiss(
    new short[,] { { 1, -1, 0 }, { 1, 1, 0 }, { 1, -1, 0 } },
    HitAndMiss.Modes.Thinning));
filterSequence.Add(new HitAndMiss(
    new short[,] { { -1, 1, -1 }, { 1, 1, 0 }, { -1, 0, 0 } },
    HitAndMiss.Modes.Thinning));
filterSequence.Add(new HitAndMiss(
    new short[,] { { 1, 1, 1 }, { -1, 1, -1 }, { 0, 0, 0 } },
    HitAndMiss.Modes.Thinning));
filterSequence.Add(new HitAndMiss(
    new short[,] { { -1, 1, -1 }, { 0, 1, 1 }, { 0, 0, -1 } },
    HitAndMiss.Modes.Thinning));
filterSequence.Add(new HitAndMiss(
    new short[,] { { 0, -1, 1 }, { 0, 1, 1 }, { 0, -1, 1 } },
    HitAndMiss.Modes.Thinning));
filterSequence.Add(new HitAndMiss(
    new short[,] { { 0, 0, -1 }, { 0, 1, 1 }, { -1, 1, -1 } },
    HitAndMiss.Modes.Thinning));

// フィルタ処理の繰り返し回数を指定
var filter = new FilterIterator(filterSequence, 20);

// 細線化処理の実行
var thinned = filter.Apply(binary);
pictureBox3.Image = thinned;

実行結果.

f:id:whoopsidaisies:20140915092901p:plain