Ejemplo n.º 1
0
        public static void CutSchnitzelImage(string folderPath, IEnumerable <Tuple <string, double> > input = null)
        {
            var path = folderPath + "pic.jpg";

            try
            {
                var mat = CvInvoke.Imread(path, ImreadModes.AnyColor);
                CvInvoke.CvtColor(mat, mat, ColorConversion.Bgr2Rgb);
                CvInvoke.CvtColor(mat, mat, ColorConversion.Rgb2Hsv);
                Image <Bgr, Byte> image = mat.ToImage <Bgr, Byte>();
                var test = image.Convert <Hsv, Byte>();
                Image <Gray, Byte>[] channels = test.Split();
                try
                {
                    var botLimit = new ScalarArray(new MCvScalar(10, 125, 75));
                    var uprLimit = new ScalarArray(new MCvScalar(15, 255, 255));

                    var contours = new VectorOfVectorOfPoint();
                    Image <Hsv, byte> imageHsvDest = new Image <Hsv, byte>(image.Width, image.Width);

                    CvInvoke.InRange(mat, botLimit, uprLimit, imageHsvDest);
                    CvInvoke.FindContours(imageHsvDest, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);

                    var arrayList = new List <ContourArea>(contours.Size);
                    for (int i = 0; i < contours.Size; i++)
                    {
                        var contour = contours[i];
                        arrayList.Add(new ContourArea(CvInvoke.ContourArea(contour), contour));
                    }

                    var color          = new MCvScalar(255, 0, 0);
                    var biggestContour = arrayList.OrderByDescending(x => x.Area).FirstOrDefault();

                    if (biggestContour == null || biggestContour.Area < 1000)
                    {
                        //This is not a schnitzel
                    }

                    var mask = Mat.Zeros(imageHsvDest.Rows, imageHsvDest.Cols, DepthType.Cv8U, 3);
                    CvInvoke.DrawContours(mask, new VectorOfVectorOfPoint(biggestContour.Contour), 0, color, -1);
                    var newPicPath = DividePicture(path, mask, biggestContour.Area, input);
                    //return newPicPath;
                }
                finally
                {
                    channels[0].Dispose();
                    channels[1].Dispose();
                    channels[2].Dispose();
                }
            }
            catch (Exception e)
            {
                // do nothing
            }
        }