C#のWinFormsで画像加工アプリ14「クロージング」

コンピュータ

モルフォロジー変換のクロージング処理を行います。

ソースコード

ファイル名:Form1.Closing.cs(新規追加)

using OpenCvSharp;
using OpenCvSharp.Extensions;

namespace GazouKakou02;
public partial class Form1 : Form
{
    // メニュー項目
    readonly ToolStripMenuItem closingMenuItem = new()
    {
        Text = "クロージング",
    };
    
    /// <summary>
    /// クロージングフィルタの初期化
    /// </summary>
    public void Init_Closing()
    {
        // メニューの登録
        filterMenuItem.DropDownItems.Add(closingMenuItem);

        // フィルター(クロージングフィルタ)
        Func<Bitmap, int, Task<Bitmap>> filter = new(async (src, th) =>
        {
            return await Task.Run(()=>
            {
                using Mat srcMat = BitmapConverter.ToMat(src);
                using Mat dstMat = new();

                if (srcMat.Channels() > 1)
                    Cv2.CvtColor(srcMat, srcMat, ColorConversionCodes.BGR2GRAY);
                Cv2.Threshold(srcMat, dstMat, th, 255.0d, ThresholdTypes.Binary);
                var kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(5,5));

                Cv2.MorphologyEx(dstMat, dstMat, MorphTypes.Close, kernel);

                return BitmapConverter.ToBitmap(dstMat);
            });
        });

        // メニューアイテムのクリックイベント
        closingMenuItem.Click += (s, e) =>
        {
            if (_buffBmp is null) return;

            var dialog = new FilterDialog();

            dialog.Load += (s, e) =>
            {
                dialog.Track1.Maximum = 255;
                dialog.Track1.Minimum = 0;
                dialog.Track1.Value = 127;
            };

            bool filterFlag = false;
            dialog.OkBtn.Enabled = !filterFlag;
            Bitmap? bmp = null;
            dialog.Track1.ValueChanged += async (s, e) =>
            {
                dialog.Track1Label.Text = string.Format("th:{0}", dialog.Track1.Value);
                if (filterFlag)
                {
                    // フィルター実行中につきキャンセル
                    return;
                }

                filterFlag = true;
                var backupValue = dialog.Track1.Value;
                var currentValue = backupValue;
                do
                {
                    backupValue = currentValue;

                    int th = currentValue;
                    bmp = await filter(_buffBmp, th);
                    dialog.Picbox.Image?.Dispose();
                    dialog.Picbox.Image = bmp;

                    currentValue = dialog.Track1.Value;
                } while( currentValue != backupValue);

                filterFlag = false;
                dialog.OkBtn.Enabled = !filterFlag;
            };

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                // OK
                this.Bmp = bmp;
            } else {
                // Cancel
                bmp?.Dispose();
            }
        };
    }
}

画像が表示されている状態でメインメニュー「フィルター」→「クロージング」を選ぶ

コメント