opencvSharp4学习1 安装,读取,灰度,轮廓检测

wpf 使用opencvSharp,需要nuget安装四个库

opencvSharp4学习1 安装,读取,灰度,轮廓检测_第1张图片

 

 Mat imgscr = Cv2.ImRead(fName);//读取图像

            // Read image and preprocess

            //转换为灰度图像
            Mat gray = new Mat();
            
            //参数:1 原图矩阵容器 2:保存图像的矩阵容器 3:颜色转换通道(很多,查手册)
            Cv2.CvtColor(imgscr, gray, ColorConversionCodes.RGB2GRAY); //转为灰度空间图像,

            Mat outImage = new Mat(); //声明一个容器,装载改变后的图像

            Mat blur = new Mat();
            OpenCvSharp.Size ksize = new OpenCvSharp.Size(3, 3);
            Cv2.GaussianBlur(gray, blur, ksize, 0);

            //show_images([gray, blur])

            Mat edged = new Mat();
            //edged = cv2.Canny(blur, 50, 100)
            Cv2.Canny(blur, edged, 30, 90);

           
            Mat s1 = new Mat();

            int  size = 3 * 2 + 1; //要为奇数
            Mat se = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(size, size), new OpenCvSharp.Point(-1, -1));

            //膨胀
            Cv2.Dilate(edged, s1, se, new OpenCvSharp.Point(-1, -1), 1);

            Cv2.Erode(s1, s1, se, new OpenCvSharp.Point(-1, -1), 1);


           

            //获得轮廓
            OpenCvSharp.Point[][] contours;
            HierarchyIndex[] hierarchly;
            Cv2.FindContours(s1, out contours, out hierarchly, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple, new OpenCvSharp.Point(0, 0));

            //将结果画出并返回结果
            Mat dst_Image = Mat.Zeros(s1.Size(), s1.Type());
            Random rnd = new Random();
            for (int i = 0; i < contours.Length; i++)
            {
                Scalar color = new Scalar(255, 0, 250);
                Cv2.DrawContours(imgscr, contours, i, color, 2, LineTypes.Link8, hierarchly);
            }
            ///(1)转为 bitmap:
            cnt.Content = "计数:" + contours.Length;

            BitmapSource map = OpenCvSharp.WpfExtensions.BitmapSourceConverter.ToBitmapSource(imgscr);

            outImg.Source = map;

你可能感兴趣的:(wpf,microsoft)