OpenCVSharp「ノンローカルミーンフィルタ(グレースケール)」を試す。

C#コンピュータ
C#
スポンサーリンク

プロジェクトの作成

ソースプログラム

using OpenCvSharp;
using OpenCvSharp.Extensions;

namespace fastNlMeansDenoisingSample;

public partial class Form1 : Form
{
    Bitmap? _bmp  = null;

    // フィルター(fastNlMeansDenoisingフィルター)
    static Bitmap Filter(Bitmap b, float h)
    {
        using var mat = BitmapConverter.ToMat(b);
        switch(b.PixelFormat) {
            case System.Drawing.Imaging.PixelFormat.Format24bppRgb:
                Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2GRAY);
                break;
            case System.Drawing.Imaging.PixelFormat.Format32bppRgb:
            case System.Drawing.Imaging.PixelFormat.Format32bppArgb:
                Cv2.CvtColor(mat, mat, ColorConversionCodes.BGRA2GRAY);
                break;
        };
        Cv2.FastNlMeansDenoising(mat, mat, h);
        return BitmapConverter.ToBitmap(mat);
    }

    public Form1()
    {
        InitializeComponent();

        Text = "fastNlMeansDenoisingフィルター";

        var sc = new SplitContainer {
            Dock = DockStyle.Fill,
            Orientation = Orientation.Horizontal,   // 上下
            Panel1MinSize = 100,
        };
        var picbox = new PictureBox {
            Dock = DockStyle.Fill,
            AllowDrop = true,
            SizeMode = PictureBoxSizeMode.Zoom,
        };
        picbox.DragEnter += (o, e) => {
            if (e.Data == null) return;
            if(!e.Data.GetDataPresent(DataFormats.FileDrop)) return;
            e.Effect = DragDropEffects.Copy;
        };
        var toClip = new Button {
            Text = "コピー",
            Location = new System.Drawing.Point(10, 10),
            Size = new System.Drawing.Size(180, 50),
        };
        var fromClip = new Button {
            Text = "貼り付け",
            Location = new System.Drawing.Point(200, 10),
            Size = new System.Drawing.Size(180, 50),
        };
        var filterExec = new RadioButton {
            Text = "フィルターOFF",
            Appearance = Appearance.Button,
            AutoCheck = false,
            Location = new System.Drawing.Point(410, 10),
            Size = new System.Drawing.Size(180, 50),
        };
        var hTrack = new TrackBar {
            Minimum = 1,
            Maximum = 20,
            Value = 3,
            Location = new System.Drawing.Point(80, 80),
            Size = new System.Drawing.Size(360, 50),
        };
        var hLabel = new Label {
            Text = "H:" + hTrack.Value,
            Location = new System.Drawing.Point(10, 80),
            Size = new System.Drawing.Size(120, 50),
        };

        Action<Bitmap> SetPicboxImage = ((Bitmap bmp) => {
            using var mat = BitmapConverter.ToMat(bmp);
            if (picbox.Image is not null) picbox.Image.Dispose();
            picbox.Image = BitmapConverter.ToBitmap(mat);
        });
        Action ResetBitmap = (()=>{
            if (_bmp is null) return;
            SetPicboxImage(_bmp);
        });
        Action<Bitmap> SetBitmap = ((Bitmap src) => {
            if (_bmp is not null) _bmp.Dispose();
            _bmp = src;
            ResetBitmap();
            filterExec.Checked = false;
        });

        picbox.DragDrop += (sender, e) => {
            // ファイルドロップ
            if (e.Data == null) return;
            if(!e.Data.GetDataPresent(DataFormats.FileDrop)) return;
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            if (files.Length < 1) return;

            // 読み込み
            using var fs = new System.IO.FileStream(
                files[0], System.IO.FileMode.Open,  System.IO.FileAccess.Read);
            var obj = System.Drawing.Image.FromStream(fs);
            if (obj is not null) SetBitmap((Bitmap)obj);
        };
        toClip.Click += (sender, e) => {
            if (picbox.Image is null) return;
            var ms = new MemoryStream();
            picbox.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            Clipboard.SetData("PNG", ms);            
        };
        fromClip.Click += (sender, e) => {
            var obj = Clipboard.GetData("PNG");
            if (obj == null) return;
            var ms = (MemoryStream)obj;
            if (ms is not null) SetBitmap(new Bitmap(ms));
        };
        hTrack.ValueChanged += (sender, e) => {
            hLabel.Text = "H:" + hTrack.Value.ToString();
        };
        filterExec.Click += async (sender, e) => {
            if (_bmp is null) return;

            if (filterExec.Checked) {
                ResetBitmap();
                filterExec.Text = "フィルターOFF";
                filterExec.Checked = false;
            } else {
                // フィルター
                float h = (float)hTrack.Value;
                Bitmap? result = null;
                await Task.Run(()=>{
                    result = Filter(_bmp, h);
                });
                if (result != null) {
                    SetPicboxImage(result);
                    filterExec.Text = "フィルターON";
                    filterExec.Checked = true;
                }
            }
        };
        sc.Panel1.Controls.Add(picbox);
        sc.Panel2.Controls.Add(toClip);
        sc.Panel2.Controls.Add(fromClip);
        sc.Panel2.Controls.Add(filterExec);
        sc.Panel2.Controls.Add(hLabel);
        sc.Panel2.Controls.Add(hTrack);
        Controls.Add(sc);

        this.Size = new System.Drawing.Size(800, 600);
    }
}

実行

dotnet run

フィルタ適用前に見える点線の格子がフィルタ適用後は消えています。

コメント