OpenCVSharp4で輪郭検出

輪郭検出とは

cannyなどで検出したエッジから、輪郭(ループ)を取り出すこと。
OpenCVCv2.FindContours()では輪郭同士の包含関係も取り出せる

プログラム

OpenCVSharp4の導入はコチラ

using System;  
using OpenCvSharp;  

namespace Finding_contours {  
    class Program {  
        static void Main(string[] args) {  
            //画像をグレースケールとして読み込み、平滑化する  
            Mat src = new Mat(@"C:\Users\taman\source\repos\Finding_contours\Finding_contours\picture.png", ImreadModes.Grayscale);  
            src.Blur(new Size(3, 3));  

            //エッジ検出  
            Mat edge = new Mat();  
            Cv2.Canny(src, edge, 100, 200);  
            Point[][] contours;  
            HierarchyIndex[] hierarchy;  

            //輪郭検出  
            Cv2.FindContours(edge, out contours, out hierarchy, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);  

            //ランダムカラーで描画  
            Mat drawing = Mat.Zeros(edge.Size(), MatType.CV_8UC3);  
            for(int i = 0; i < contours.Length; i++) {  
                Scalar color = new Scalar(new Random().Next(0, 255), new Random().Next(0, 255), new Random().Next(0, 255));  
                Cv2.DrawContours(drawing, contours, i, color, 2, LineTypes.Link8, hierarchy, 0);  
            }  
            Cv2.ImShow("contours", drawing);  

            Cv2.WaitKey();  
        }  
    }  
}  

参考

http://labs.eecs.tottori-u.ac.jp/sd/Member/oyamada/OpenCV/html/py_tutorials/py_imgproc/py_contours/py_contours_hierarchy/py_contours_hierarchy.html
https://docs.opencv.org/4.0.0/df/d0d/tutorial_find_contours.html