1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

OpenCvを.NETで使う_OpenCvSharp4

Posted at

OpenCVが.NETで使えるライブラリを試してみました。
読込んだ画像に輪郭を描画します!

準備

vscodeでやっています。

  • dotnet new winforms -n OpenCv_winforms
  • cd OpenCv_winforms

必要なパッケージ

OpenCvSharp4
(Apache License 2.0)
https://github.com/shimat/opencvsharp

  • dotnet add package OpenCvSharp4.Windows
    • WindowsというのがAllInOneとなってるのでそれだけでいいのかなと思ったけど、Extensionsを入れないとダメなのもあるようです
  • dotnet add package OpenCvSharp4.Extensions

コード

画像の処理

適当な画像を保存して、それに輪郭を描画する。

public static void GetImage()
    {
        // 画像の読込み
        using var srcMat = new Mat(@"image\10.jpg", ImreadModes.Color);
        // 画像サイズの調整
        Cv2.Resize(srcMat, srcMat, new OpenCvSharp.Size(), 0.1, 0.1, InterpolationFlags.Area);
        // グレースケール
        var grayMat = srcMat.CvtColor(ColorConversionCodes.BGR2GRAY);
        // 大津の二値化
        var thresholdMat = grayMat.Threshold(0, 255, ThresholdTypes.Otsu);
        //平準化(中央値フィルタ)
        var mediaBlur = new Mat();
        Cv2.MedianBlur(thresholdMat, mediaBlur, 3);
        //ジャグ配列
        OpenCvSharp.Point[][] contours;
        OpenCvSharp.HierarchyIndex[] hierarchyIndexes;
        // 輪郭の取得
        // Externalは外側のみの輪郭 Listはすべて
        Cv2.FindContours(thresholdMat, out contours, out hierarchyIndexes, RetrievalModes.List, ContourApproximationModes.ApproxSimple);

        // 輪郭の描画
        Cv2.DrawContours(srcMat, contours, -1, new Scalar(0, 255, 0));
        // 画像の表示
        Cv2.ImShow("src", srcMat);
        // 画像の保存
        Cv2.ImWrite("image/src.png", srcMat);
    }

src.png

お~すごい!
今度はガタガタなのをキレイにするのもやってみたいですね。

ボタン

ボタンクリックで画像の処理を実行するようにする。

Form1.cs
    void Button_Click(object sender, EventArgs e)
    {
        OpenCvMain.GetImage();
    }
Form1.Designer.cs
private Button button1;
    private void InitializeComponent()
    {
        this.button1 = new Button();

        button1.Text = "クリック";
        button1.Location = new Point(10, 10);
        button1.Size = new Size(100, 100);
        button1.Click += new EventHandler(Button_Click);
        this.Controls.Add(button1);

        this.components = new System.ComponentModel.Container();
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(800, 450);
        this.Text = "Form1";
    }

参考

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?