Example #1
0
        /// <inheritdoc />
        /// <exception cref="ArgumentNullException">
        /// <paramref name="source"/> is <b>null</b>.
        /// </exception>
        public PointsOfInterestFeatures BuildFeatures(ImageSource source, CancellationToken cancellationToken)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            Image image = ImagePreprocessing.Process(source.Image, this.ImagePreprocessingOptions, 8);

            image = image
                    ////.Scale(null, 100.0 / image.HorizontalResolution, 100.0 / image.VerticalResolution, ScalingOptions.None)
                    ////.Binarize()
                    .Convert8To1(null, 128)
                    .CleanOverscan(0.5f, 0.5f)
                    .Deskew(null)
                    .Despeckle(null);

            ISet <ConnectedComponent> components = image.FindConnectedComponents(8);

            image.RemoveConnectedComponents(components.Where(x => x.Power <= 16));

            image = image
                    .CropBlackArea(0, 0)
                    ////.Dilate(null, StructuringElement.Square(3), 1, BorderType.BorderConst, image.WhiteColor)
                    ////.CropBlackArea(0, 0)
                    .Convert1To8(null)
                    .Erode(null, StructuringElement.Square(2), 1, BorderType.BorderRepl, 0)
                    .ScaleByDownsampling2(null)
                    .FilterLowpass(null, 3, BorderType.BorderRepl, 0);

            FeatureDetectors.Features features = this.detector.Detect(image, cancellationToken);

            return(new PointsOfInterestFeatures(source.Id, features));
        }
Example #2
0
 // foamliu, 2009/02/04, 开操作.
 //
 public static int[][] Open(int[][] mat, StructuringElement strel)
 {
     int[][] temp, output;
     Erosion(mat, strel, out temp);
     GrayScaleImageLib.MinkowskiAddtion(temp, strel, out output);
     return(output);
 }
Example #3
0
        private static void DemoDilation()
        {
            StructuringElement se  = StructuringElement.CreateSquare(3);
            Dilation           dil = new Dilation(se);

            using (StreamReader sr = new StreamReader("img.txt"))
            {
                String line;

                while ((line = sr.ReadLine()) != null)
                {
                    string source = string.Format("grayscale_img/{0}.jpg", line);
                    Bitmap bmp    = Bitmap.FromFile(source) as Bitmap;

                    Matrix img_matrix   = Matrix.FromBitmap(bmp);
                    Matrix thres_matrix = img_matrix < 100;
                    Matrix result       = dil.Execute(thres_matrix);

                    string dest = string.Format("dilation/{0}.txt", line);
                    using (StreamWriter sw = new StreamWriter(dest, false))
                    {
                        sw.Write(result.ToString());
                    }
                    result.ToBitmap().Save(string.Format("dilation/{0}.png", line));
                }
            }
        }
        public Bitmap Process(Bitmap input, ProgressBar progressBar)
        {
            var w         = new BinaryProcessor(input);
            var structure = new StructuringElement(StructuringElementShape.Rectangle, 3);

            w.Erode(structure);

            return(w.GetBitmap());
        }
        /// <summary>
        /// foamliu, 2009/02/04, 腐蚀.
        ///
        /// </summary>
        /// <param name="mat">二值图像</param>
        /// <param name="b">结构元素</param>
        public static void Erosion(int[][] mat, StructuringElement strel, out int[][] output)
        {
            //int width = mat.Length;
            //int height = mat[0].Length;

            //output = new int[width][];

            //for (int i = 0; i < width; i++)
            //{
            //    output[i] = new int[height];
            //}

            //int m = b.Width;
            //int n = b.height;

            //for (int y = 0; y < height; y++)
            //{
            //    for (int x = 0; x < width; x++)
            //    {
            //        if (mat[x][y] != 1)
            //            continue;

            //        for (int j = -n; j <= n; j++)
            //        {
            //            for (int i = -m; i <= m; i++)
            //            {
            //                if (b.B(i, j) == 0)
            //                    continue;

            //                if (Util.GetPixel(mat,x + i,y + j) == 0)
            //                    goto next;
            //            }
            //        }

            //        output[x][y] = 1;

            //    next: ;


            //    }
            //}


            // foamliu, 2009/02/06, 改用二值图像库中的算法.
            //
            // 先把 strel 求转置
            //
            StructuringElement trans = StructuringElement.Transposition(strel);

            BinaryImageLib.MinkowskiSubtraction(mat, trans, out output);
        }
        public Bitmap Process(Bitmap input, ProgressBar progressBar)
        {
            var w         = new BinaryProcessor(input);
            var structure = new StructuringElement(StructuringElementShape.Rectangle, 3);
            var x         = (BinaryProcessor)w.Clone();
            var y         = (BinaryProcessor)w.Clone();

            x.Dilate(structure);
            y.Erode(structure);
            y.Complement();
            x.And(y);

            return(x.GetBitmap());
        }
        public virtual void Dilate(StructuringElement structure)
        {
            // We assume that the hotspot of the structuring element is in
            // the middle.
            var hotspotX = (int)(structure.Size) / 2;
            var hotspotY = (int)(structure.Size) / 2;
            var buffer   = (int[, ])Image.Clone();

            for (int x = 0; x < Width; x++)
            {
                for (int y = 0; y < Height; y++)
                {
                    var structuredSums = new List <int>();

                    for (int u = 0; u < structure.Size; u++)
                    {
                        for (int v = 0; v < structure.Size; v++)
                        {
                            if (structure[u, v] > 0)
                            {
                                var p = x + u - hotspotX;
                                var q = y + v - hotspotY;

                                if (p >= 0 & q >= 0 & p < Width & q < Height)
                                {
                                    structuredSums.Add(processStructure(Image[p, q], structure[u, v]));
                                }
                            }
                        }
                    }

                    var structuredMax = structuredSums.Max();

                    if (structuredMax < 0)
                    {
                        structuredMax = 0;
                    }
                    else if (structuredMax > 255)
                    {
                        structuredMax = 255;
                    }

                    buffer[x, y] = structuredMax;
                }
            }
            Image = buffer;
        }
Example #8
0
        /// <summary>
        /// foamliu, 2009/02/04, 灰度值腐蚀.
        ///
        /// </summary>
        /// <param name="mat">灰度图像</param>
        /// <param name="b">结构元素</param>
        public static void Erosion(int[][] mat, StructuringElement strel, out int[][] output)
        {
            //int width = mat.Length;
            //int height = mat[0].Length;

            //output = new int[width][];

            //for (int i = 0; i < width; i++)
            //{
            //    output[i] = new int[height];
            //}

            //int m = b.Length;
            //int n = b[0].Length;

            //for (int y = 0; y < height; y++)
            //{
            //    for (int x = 0; x < width; x++)
            //    {
            //        int min = int.MaxValue;
            //        for (int j = 0; j < n; j++)
            //        {
            //            for (int i = 0; i < m; i++)
            //            {
            //                int matxy = Util.GetPixel(mat, x - i, y - j);
            //                if (matxy + b[i][j] < min)
            //                {
            //                    min = matxy + b[i][j];
            //                }
            //            }
            //        }

            //        output[x][y] = min;
            //    }
            //}


            // foamliu, 2009/02/06, 改用二值图像库中的算法.
            //
            // 先把 strel 求转置
            //
            StructuringElement trans = StructuringElement.Transposition(strel);

            GrayScaleImageLib.MinkowskiSubtraction(mat, trans, out output);
        }
        /// <summary>
        /// foamliu, 2009/02/05, 抽取骨骼.
        ///
        /// 主要参照:
        ///
        ///     佳奇发给我 Morphological Image Process 幻灯中倒数第三页: Skeleton Equations.
        ///
        /// </summary>
        public static void ExtractSkeleton(int[][] mat, StructuringElement strel, out int[][] output)
        {
            int width  = mat.Length;
            int height = mat[0].Length;

            int[][] temp = (int[][])mat.Clone();
            int     K    = CalcK(mat, strel);

            int[][] Sk;
            output = Util.BuildMatInt(width, height);

            for (int k = 1; k <= K; k++)
            {
                temp = BinaryImageLib.MinkowskiSubtraction(temp, strel);
                Sk   = BinaryImageLib.Difference(temp, BinaryImageLib.Open(temp, strel));
                BinaryImageLib.Union(output, Sk);
            }
        }
Example #10
0
        // 计算 Skeleton Equations 中的 K.
        //
        private static int CalcK(int[][] mat, StructuringElement strel)
        {
            int[][] temp = (int[][])mat.Clone();
            int     k    = 0;

            while (true)
            {
                temp = BinaryImageLib.MinkowskiSubtraction(temp, strel);
                if (BinaryImageLib.Empty(temp))
                {
                    break;
                }
                else
                {
                    k++;
                }
            }

            return(k);
        }
        public override void Dilate(StructuringElement structure)
        {
            // We assume that the hotspot of the structuring element is in
            // the middle.
            var hotspotX = (int)(structure.Size) / 2;
            var hotspotY = (int)(structure.Size) / 2;
            var buffer   = new BinaryProcessor(this.Width, this.Height);

            for (int u = 0; u < structure.Size; u++)
            {
                for (int v = 0; v < structure.Size; v++)
                {
                    if (structure[u, v] > 0)
                    {
                        buffer.Max(this, u - hotspotX, v - hotspotY);
                    }
                }
            }
            this.Image = buffer.Image;
        }
Example #12
0
        public Bitmap Process(Bitmap input, ProgressBar progressBar)
        {
            var p    = new ImageProcessor(input);
            var s1   = new StructuringElement(StructuringElementShape.Rectangle, 5);
            var s2   = new StructuringElement(StructuringElementShape.Rectangle, 9);
            var mask = new BinaryProcessor(_filter.Process(input, progressBar));

            mask.Close(s1);
            mask.Open(s1);
            p.Mask(mask);

            mask.Dilate(s2);


            var bt  = new BoundaryTrace(s1);
            var bmp = bt.Process(mask.GetBitmap(), progressBar);
            var p2  = new BinaryProcessor(bmp);

            //p.Layer(p2);

            return(p.GetBitmap());
        }
Example #13
0
        public void ErodeTest1()
        {
            const int Width  = 150;
            const int Height = 20;

            for (int ix = 0; ix < Width; ix++)
            {
                for (int iy = 0; iy < Height; iy++)
                {
                    Image image = new Image(Width, Height, 1, 200, 200);
                    image.SetBlack();
                    image.SetPixel(ix, iy, 0);

                    Image dilatedImage = image.Erode(null, StructuringElement.Square(3), 1, BorderType.BorderConst, uint.MaxValue);

                    if ((ix == 0 || ix == Width - 1) && (iy == 0 || iy == Height - 1))
                    {
                        Assert.AreEqual(
                            (ulong)((Width * Height) - 4),
                            dilatedImage.Power(),
                            string.Format(CultureInfo.InvariantCulture, "{0} {1}", ix, iy));
                    }
                    else if ((ix == 0 || ix == Width - 1) || (iy == 0 || iy == Height - 1))
                    {
                        Assert.AreEqual(
                            (ulong)((Width * Height) - 6),
                            dilatedImage.Power(),
                            string.Format(CultureInfo.InvariantCulture, "{0} {1}", ix, iy));
                    }
                    else
                    {
                        Assert.AreEqual(
                            (ulong)((Width * Height) - 9),
                            dilatedImage.Power(),
                            string.Format(CultureInfo.InvariantCulture, "{0} {1}", ix, iy));
                    }
                }
            }
        }
Example #14
0
        public void DilateTest_3x3()
        {
            const int Width  = 150;
            const int Height = 20;

            for (int ix = 0; ix < Width; ix++)
            {
                for (int iy = 0; iy < Height; iy++)
                {
                    Image image = new Image(Width, Height, 1, 200, 200);
                    image.SetPixel(ix, iy, 1);

                    Image dilatedImage = image.Dilate(null, StructuringElement.Square(3), 1, BorderType.BorderConst, image.WhiteColor);

                    if ((ix == 0 || ix == Width - 1) && (iy == 0 || iy == Height - 1))
                    {
                        Assert.AreEqual(
                            4ul,
                            dilatedImage.Power(),
                            string.Format(CultureInfo.InvariantCulture, "{0} {1}", ix, iy));
                    }
                    else if ((ix == 0 || ix == Width - 1) || (iy == 0 || iy == Height - 1))
                    {
                        Assert.AreEqual(
                            6ul,
                            dilatedImage.Power(),
                            string.Format(CultureInfo.InvariantCulture, "{0} {1}", ix, iy));
                    }
                    else
                    {
                        Assert.AreEqual(
                            9ul,
                            dilatedImage.Power(),
                            string.Format(CultureInfo.InvariantCulture, "{0} {1}", ix, iy));
                    }
                }
            }
        }
Example #15
0
        public void CloseTest_3x2()
        {
            const int Width  = 7;
            const int Height = 7;
            Rectangle bounds = new Rectangle(2, 2, 3, 3);

            foreach (int bitsPerPixel in new[] { 1, /*2, 4,*/ 8, 16, 24, 32 })
            {
                Image image = new Image(Width, Height, bitsPerPixel, 200, 200);
                image.SetWhite();
                image.SetBlack(bounds);

                Image closing = image.MorphClose(null, StructuringElement.Brick(2, 2), 1, BorderType.BorderConst, image.WhiteColor);

                for (int ix = 0; ix < Width; ix++)
                {
                    for (int iy = 0; iy < Height; iy++)
                    {
                        Assert.AreEqual(bounds.Contains(ix, iy) ? image.BlackColor : image.WhiteColor, closing.GetPixel(ix, iy));
                    }
                }
            }
        }
Example #16
0
 /// <summary>
 /// Initializes a new instance of the BinaryHitMiss class with 
 /// the given <see cref="StructuringElement"/> objects.
 /// </summary>
 /// <param name="se1">
 /// The <see cref="StructuringElement"/> to use for binary 
 /// hit-miss.
 /// </param>
 /// <param name="se2">
 /// The <see cref="StructuringElement"/> to use for binary 
 /// hit-miss.
 /// </param>
 public BinaryHitMiss (StructuringElement se1, 
         StructuringElement se2)
 {
         this.se1 = se1;
         this.se2 = se2;
 }
Example #17
0
 /// <summary>
 /// Initializes a new instance of the Closing class with the
 /// given <see cref="StructuringElement"/>.
 /// </summary>
 /// <param name="se">
 /// The <see cref="StructuringElement"/> to use for closing.
 /// </param>
 public Closing(StructuringElement se)
 {
     this.se = se;
 }
 public void Erode(StructuringElement structure)
 {
     this.Complement();
     this.Dilate(structure.Reflection);
     this.Complement();
 }
 public void Close(StructuringElement structure)
 {
     this.Dilate(structure);
     this.Erode(structure);
 }
Example #20
0
        public static PaletteType ProcessImage(VisionImage image, string path, out double[] distance)
        {
            // Initialize the IVA_Data structure to pass results and coordinate systems.
            IVA_Data ivaData = new IVA_Data(17, 1);

            distance = new double[4] {
                0, 0, 0, 0
            };

            // Creates a new, empty region of interest.
            Roi roi = new Roi();
            // Creates a new AnnulusContour using the given values.
            PointContour   vaCenter = new PointContour(1283, 965);
            AnnulusContour vaOval   = new AnnulusContour(vaCenter, 418, 702, 0, 0);

            roi.Add(vaOval);
            // Find Circular Edge
            EdgeOptions vaOptions = new EdgeOptions();

            vaOptions.ColumnProcessingMode = ColumnProcessingMode.Average;
            vaOptions.InterpolationType    = InterpolationMethod.Bilinear;
            vaOptions.KernelSize           = 3;
            vaOptions.MinimumThreshold     = 18;
            vaOptions.Polarity             = EdgePolaritySearchMode.Rising;
            vaOptions.Width = 3;
            CircularEdgeFitOptions vaFitOptions = new CircularEdgeFitOptions();

            vaFitOptions.ProcessType    = RakeProcessType.GetFirstEdges;
            vaFitOptions.StepSize       = 7;
            vaFitOptions.MaxPixelRadius = 3;

            vaCircularEdgeReport = IVA_FindCircularEdge(image, roi, SpokeDirection.InsideToOutside, vaOptions, vaFitOptions, ivaData, 1);

            roi.Dispose();

            // Set Coordinate System
            int             vaCoordSystemIndex    = 0;
            int             stepIndexOrigin       = 1;
            int             resultIndexOrigin     = 0;
            int             stepIndexAngle        = -1;
            int             resultIndexAngle      = 0;
            double          refSysOriginX         = vaCircularEdgeReport.Center.X;
            double          refSysOriginY         = vaCircularEdgeReport.Center.Y;
            double          refSysAngle           = 0;
            AxisOrientation refSysAxisOrientation = AxisOrientation.Direct;
            int             vaCoordSystemType     = 0;

            IVA_CoordSys(vaCoordSystemIndex, stepIndexOrigin, resultIndexOrigin, stepIndexAngle, resultIndexAngle, refSysOriginX, refSysOriginY, refSysAngle, refSysAxisOrientation, vaCoordSystemType, ivaData);

            // Image Buffer: Push
            Functions.IVA_PushBuffer(ivaData, image, 0);

            // Get Image
            string          vaFilePath = path;
            FileInformation vaFileInfo = Algorithms.GetFileInformation(vaFilePath);

            // Set the image size to 0 to speed up the cast.
            //image.SetSize(0, 0);
            //image.Type = vaFileInfo.ImageType;
            //image.BitDepth = 0;
            image.ReadFile(vaFilePath);

            switch (image.Type)
            {
            case ImageType.I16:
            case ImageType.U16:
                if (image.BitDepth == 0 & false)
                {
                    image.BitDepth = 10;
                }
                break;

            default:
                break;
            }
            // Operators: Absolute Difference Image
            Algorithms.AbsoluteDifference(image, Functions.IVA_GetBuffer(ivaData, 0), image);

            // Creates a new, empty region of interest.
            Roi roi2 = new Roi();
            // Creates a new AnnulusContour using the given values.
            PointContour   vaCenter2 = new PointContour(vaCircularEdgeReport.Center.X, vaCircularEdgeReport.Center.Y);
            AnnulusContour vaOval2   = new AnnulusContour(vaCenter2, 527, 846, 0, 0);

            roi2.Add(vaOval2);
            // Reposition the region of interest based on the coordinate system.
            int coordSystemIndex = 0;

            Algorithms.TransformRoi(roi2, new CoordinateTransform(ivaData.baseCoordinateSystems[coordSystemIndex], ivaData.MeasurementSystems[coordSystemIndex]));
            // Mask from ROI
            IVA_Mask_From_ROI(image, roi2, false, false);
            roi2.Dispose();

            // Color Threshold
            Range plane1Range = new Range(0, 60);
            Range plane2Range = new Range(0, 50);
            Range plane3Range = new Range(0, 255);

            using (VisionImage thresholdImage = new VisionImage(ImageType.U8, 7))
            {
                Algorithms.ColorThreshold(image, thresholdImage, ColorMode.Rgb, 1, plane1Range, plane2Range, plane3Range);
                Algorithms.Copy(thresholdImage, image);
            }

            // Truncates the frequencies of an image.
            IVA_FFT_Truncate(image, TruncateMode.High, 7);

            // Advanced Morphology: Remove Objects
            int[] vaCoefficients            = { 1, 1, 1, 1, 1, 1, 1, 1, 1 };
            StructuringElement vaStructElem = new StructuringElement(3, 3, vaCoefficients);

            vaStructElem.Shape = StructuringElementShape.Square;
            // Filters particles based on their size.
            Algorithms.RemoveParticle(image, image, 30, SizeToKeep.KeepLarge, Connectivity.Connectivity8, vaStructElem);

            // Invert Binary Image.
            IVA_BinaryInverse(image);

            // Advanced Morphology: Remove Objects
            int[] vaCoefficients2            = { 1, 1, 1, 1, 1, 1, 1, 1, 1 };
            StructuringElement vaStructElem2 = new StructuringElement(3, 3, vaCoefficients2);

            vaStructElem.Shape = StructuringElementShape.Square;
            // Filters particles based on their size.
            Algorithms.RemoveParticle(image, image, 5, SizeToKeep.KeepLarge, Connectivity.Connectivity8, vaStructElem2);

            // Basic Morphology - Applies morphological transformations to binary images.
            int[] vaCoefficients3            = { 0, 1, 0, 1, 1, 1, 0, 1, 0 };
            StructuringElement vaStructElem3 = new StructuringElement(3, 3, vaCoefficients3);

            vaStructElem.Shape = StructuringElementShape.Square;
            // Applies morphological transformations
            for (int i = 0; i < 3; ++i)
            {
                Algorithms.Morphology(image, image, MorphologyMethod.Erode, vaStructElem3);
            }

            // Advanced Morphology: Fill Holes
            VisionImage image1 = new VisionImage();

            Algorithms.FillHoles(image, image1, Connectivity.Connectivity8);

            // Particle Analysis - Computes the number of particles detected in a binary image and
            // returns the requested measurements about the particles.
            Collection <MeasurementType> vaPixelMeasurements      = new Collection <MeasurementType>(new MeasurementType[] { MeasurementType.Area });
            Collection <MeasurementType> vaCalibratedMeasurements = new Collection <MeasurementType>(new MeasurementType[] { });

            IVA_Particle(image1, Connectivity.Connectivity8, vaPixelMeasurements, vaCalibratedMeasurements, ivaData, 16, out vaParticleReport, out vaParticleReportCalibrated);
            double[,] area = vaParticleReport.PixelMeasurements;
            double Maxarea = 0;

            for (int i = 0; i < area.GetLength(0); i++)
            {
                for (int j = 0; j < area.GetLength(1); j++)
                {
                    if (area[i, j] > Maxarea)
                    {
                        Maxarea = area[i, j];
                    }
                }
            }
            image1.Dispose();

            if (Maxarea > 1000000)
            {
                // Creates a new, empty region of interest.
                Roi roi3 = new Roi();
                // Creates a new AnnulusContour using the given values.
                PointContour   vaCenter3 = new PointContour(1295, 963);
                AnnulusContour vaOval3   = new AnnulusContour(vaCenter3, 496, 892, 0, 0);
                roi3.Add(vaOval3);
                // Reposition the region of interest based on the coordinate system.
                int coordSystemIndex2 = 0;
                Algorithms.TransformRoi(roi3, new CoordinateTransform(ivaData.baseCoordinateSystems[coordSystemIndex2], ivaData.MeasurementSystems[coordSystemIndex2]));
                // Extract the contour edges from the image
                CurveParameters            vaCurveParams         = new CurveParameters(ExtractionMode.NormalImage, 1, EdgeFilterSize.ContourTracing, 30, 20, 10, true);
                double[]                   vaConstraintMinArray  = { };
                double[]                   vaConstraintMaxArray  = { };
                ConnectionConstraintType[] vaConstraintTypeArray = { };
                ExtractContourReport       vaExtractReport       = IVA_ExtractContour(image, roi3, ExtractContourDirection.AnnulusOuterInner, vaCurveParams, vaConstraintTypeArray, vaConstraintMinArray, vaConstraintMaxArray, ExtractContourSelection.Closest);
                // Fit a circle to the contour
                ContourOverlaySettings vaEquationOverlay = new ContourOverlaySettings(true, Rgb32Value.GreenColor, 1, true);
                ContourOverlaySettings vaPointsOverlay   = new ContourOverlaySettings(true, Rgb32Value.RedColor, 1, true);
                PartialCircle          vaCircleReport    = Algorithms.ContourFitCircle(image, 100, true);
                Algorithms.ContourOverlay(image, image, vaPointsOverlay, vaEquationOverlay);
                ComputeDistanceReport vaDistanceReport = Algorithms.ContourComputeDistances(image, image, 0);

                MaxDistance      = 0;
                MaxDistanceIndex = 0;
                for (int i = 0; i < vaDistanceReport.Distances.Count; i++)
                {
                    if (vaDistanceReport.Distances[i].Distance > MaxDistance)
                    {
                        MaxDistance      = vaDistanceReport.Distances[i].Distance;
                        MaxDistanceIndex = i;
                    }
                }
                var pos = vaDistanceReport.Distances[MaxDistanceIndex];
                distance[0] = MaxDistance;

                roi3.Dispose();

                // Creates a new, empty region of interest.
                Roi roi4 = new Roi();
                // Creates a new AnnulusContour using the given values.
                PointContour   vaCenter4 = new PointContour(1294, 962);
                AnnulusContour vaOval4   = new AnnulusContour(vaCenter4, 499, 885, 0, 0);
                roi4.Add(vaOval4);
                // Reposition the region of interest based on the coordinate system.
                int coordSystemIndex3 = 0;
                Algorithms.TransformRoi(roi4, new CoordinateTransform(ivaData.baseCoordinateSystems[coordSystemIndex3], ivaData.MeasurementSystems[coordSystemIndex3]));
                // Extract the contour edges from the image
                CurveParameters            vaCurveParams2         = new CurveParameters(ExtractionMode.NormalImage, 1, EdgeFilterSize.ContourTracing, 30, 25, 10, true);
                double[]                   vaConstraintMinArray2  = { };
                double[]                   vaConstraintMaxArray2  = { };
                ConnectionConstraintType[] vaConstraintTypeArray2 = { };
                ExtractContourReport       vaExtractReport2       = IVA_ExtractContour(image, roi4, ExtractContourDirection.AnnulusInnerOuter, vaCurveParams2, vaConstraintTypeArray2, vaConstraintMinArray2, vaConstraintMaxArray2, ExtractContourSelection.Closest);
                // Fit a circle to the contour
                ContourOverlaySettings vaEquationOverlay2 = new ContourOverlaySettings(true, Rgb32Value.GreenColor, 1, true);
                ContourOverlaySettings vaPointsOverlay2   = new ContourOverlaySettings(true, Rgb32Value.RedColor, 1, true);
                PartialCircle          vaCircleReport2    = Algorithms.ContourFitCircle(image, 100, true);
                Algorithms.ContourOverlay(image, image, vaPointsOverlay2, vaEquationOverlay2);
                ComputeDistanceReport vaDistanceReport2 = Algorithms.ContourComputeDistances(image, image, 0);

                MaxDistance1      = 0;
                MaxDistanceIndex1 = 0;
                for (int i = 0; i < vaDistanceReport2.Distances.Count; i++)
                {
                    if (vaDistanceReport2.Distances[i].Distance > MaxDistance1)
                    {
                        MaxDistance1      = vaDistanceReport2.Distances[i].Distance;
                        MaxDistanceIndex1 = i;
                    }
                }
                var pos1 = vaDistanceReport2.Distances[MaxDistanceIndex1];
                distance[1] = MaxDistance1;
                distance[2] = (vaCircleReport2.Center.X - vaCircularEdgeReport.Center.X) / 96;
                distance[3] = (vaCircleReport2.Center.Y - vaCircularEdgeReport.Center.Y) / 96;
                roi4.Dispose();
            }
            else
            {
                distance[0] = 9999;
                distance[1] = 9999;
                distance[2] = 9999;
                distance[3] = 9999;
            }

            // Dispose the IVA_Data structure.
            ivaData.Dispose();
            if (path == $"{ @"./ImageTemp/temp.jpg"}")
            {
                image.Dispose();
            }

            // Return the palette type of the final image.
            return(PaletteType.Binary);
        }
Example #21
0
 /// <summary>
 /// Initializes a new instance of the Erosion class with the
 /// given <see cref="StructuringElement"/>.
 /// </summary>
 /// <param name="se">
 /// The <see cref="StructuringElement"/> to use for erosion.
 /// </param>
 public Erosion (StructuringElement se)
 {
         this.se = se;
 }
Example #22
0
        public void XXXTest()
        {
#if false
            const int Count     = 10000000;
            Stopwatch stopwatch = new Stopwatch();

            RandomGenerator random = new RandomGenerator();

            int     length = 128;
            float[] dense1 = random.Generate(length);
            float[] dense2 = new float[length];
            for (int i = 0; i < 16; i++)
            {
                dense2[(int)random.Generate(0, length)] = random.Generate();
            }

            SparseVectorF sparse = SparseVectorF.FromDense(length, dense2, 0);

            stopwatch.Restart();

            for (int i = 0; i < Count; i++)
            {
                Math32f.EuclideanDistance(length, dense1, 0, dense2, 0);
            }

            stopwatch.Stop();

            Console.WriteLine("{0:F4} ms", stopwatch.ElapsedMilliseconds /* / Count*/);

            stopwatch.Restart();

            for (int i = 0; i < Count; i++)
            {
                sparse.EuclideanDistance(dense1, 0);
            }

            stopwatch.Stop();

            Console.WriteLine("{0:F4} ms", stopwatch.ElapsedMilliseconds /* / Count*/);
#else
            const int Count     = 5;
            Stopwatch stopwatch = new Stopwatch();

            ////Image image = new Image(2000, 3000, 8, 200, 200);
            ////image.Randomize();

            ////foreach ((Image image, _, _) in Image.FromFile(@"C:\DNN\dnn\test.jpg"))
            ////foreach ((Image image, _, _) in Image.FromFile(@"C:\DNN\dnn\363978.tif"))
            foreach ((Image image, _, _) in Imaging.Image.FromFile(@"L:\FormXtra\Receipts\Concur\Full\jpg\Work\08240EB488FE324E83C7C54042D9813C.jpg"))
            {
                stopwatch.Restart();

                Image xxx = image.ConvertTo(null, 8);

                for (int i = 0; i < Count; i++)
                {
                    xxx.Erode(xxx, StructuringElement.Square(2), 1, BorderType.BorderRepl, 0);
                    xxx.ScaleByDownsampling2(xxx);
                    ////image.Binarize(null, 0, 0, 0, 0, true, 0, 0);
                    ////IntegralImage.FromImage(image);

                    ////long power = image.Power();
                    ////Histogram hyst = image.GrayHistogram();

                    /*Image workImage = image
                     *  .ConvertTo(null, 8)
                     *  .Scale(null, 100.0 / image.HorizontalResolution, 100.0 / image.VerticalResolution, ScalingOptions.None)
                     *  ////.Binarize(null)
                     *  .Convert8To1(null, 128)
                     *  .CleanOverscan(0.5f, 0.5f)
                     *  .Deskew(null)
                     *  .Despeckle(null);
                     *
                     * ISet<ConnectedComponent> components = workImage.FindConnectedComponents(8);
                     * workImage.RemoveConnectedComponents(components);*/

                    /*workImage = workImage.Scale(100.0 / image.HorizontalResolution, 100.0 / image.VerticalResolution, Imaging.ScalingOptions.None);
                     * workImage = workImage.Binarize();
                     * ////workImage = workImage.Convert8To1(128);
                     * workImage = workImage.Dilate(StructuringElement.Rectangle(5, 1), 1);
                     * workImage = workImage.Dilate(StructuringElement.Rectangle(1, 5), 1);
                     * workImage = workImage.Convert1To8();
                     *
                     * DenseVectorPackF vectors = workImage.HOG(8, 2, 1, 9, 0.2f);
                     *
                     * vectors = DenseVectorPackF.Pack(vectors.Unpack().Where(x => x.Sum() != 0.0f).ToList());*/
                    ////Image temp = image.Binarize();
                }

                stopwatch.Stop();
            }

            Console.WriteLine("{0:F4} ms", stopwatch.ElapsedMilliseconds / Count);
#endif
        }
Example #23
0
        public void DilateTest2()
        {
            StructuringElement[] ses = new[]
            {
                StructuringElement.Brick(3, 1),
                StructuringElement.Brick(1, 3),
                StructuringElement.Brick(1, 4),
                StructuringElement.Brick(1, 4, new Point(0, 1)),
                StructuringElement.Square(7),
                StructuringElement.Brick(8, 6),
                StructuringElement.Brick(8, 6, new Point(6, 5)),
                StructuringElement.Brick(8, 6, new Point(10, 8)),
                StructuringElement.Cross(10, 5),
                StructuringElement.Cross(10, 5, new Point(-3, -2)),
            };

            foreach (int bitsPerPixel in new[] { 1, /*2, 4,*/ 8, 16, 24, 32 })
            {
                foreach (int width in new[] { 64 * 2, 131 })
                {
                    Image src = new Image(width, 50, bitsPerPixel, 200, 200);

                    foreach (StructuringElement se in ses)
                    {
                        // constant border
                        foreach (uint borderValue in new[] { src.BlackColor, src.WhiteColor, (uint)(((ulong)src.BlackColor + (ulong)src.WhiteColor) / 2) })
                        {
                            src.Randomize();
                            Image dst = src.Dilate(null, se, 1, BorderType.BorderConst, borderValue);

                            for (int x = 0; x < src.Width; x++)
                            {
                                for (int y = 0; y < src.Height; y++)
                                {
                                    Assert.AreEqual(ComputePixelBorder(x, y, borderValue), dst.GetPixel(x, y));
                                }
                            }
                        }

                        // replica border
                        {
                            src.Randomize();
                            Image dst = src.Dilate(null, se, 1, BorderType.BorderRepl, 0);

                            for (int x = 0; x < src.Width; x++)
                            {
                                for (int y = 0; y < src.Height; y++)
                                {
                                    Assert.AreEqual(ComputePixel(x, y), dst.GetPixel(x, y));
                                }
                            }
                        }

                        uint ComputePixel(int x, int y)
                        {
                            uint maxcolor = uint.MinValue;

                            foreach (Point point in se.GetElements())
                            {
                                Point pt = new Point(x + point.X, y + point.Y);
                                if (src.Bounds.Contains(pt))
                                {
                                    maxcolor = Color.Max(maxcolor, src.GetPixel(pt), bitsPerPixel);
                                }
                            }

                            return(maxcolor);
                        }

                        uint ComputePixelBorder(int x, int y, uint borderValue)
                        {
                            uint maxcolor = uint.MinValue;

                            foreach (Point point in se.GetElements())
                            {
                                Point pt    = new Point(x + point.X, y + point.Y);
                                uint  color = src.Bounds.Contains(pt) ? src.GetPixel(pt) : borderValue;
                                maxcolor = Color.Max(maxcolor, color, bitsPerPixel);
                            }

                            return(maxcolor);
                        }
                    }
                }
            }
        }
Example #24
0
 public Open(StructuringElement structure)
 {
     this._structure = structure;
 }
        public PaletteType ProcessImage(VisionImage image)
        {
            //vaParticleReportCalibrated = new ParticleMeasurementsReport();
            // Initialize the IVA_Data structure to pass results and coordinate systems.
            IVA_Data ivaData = new IVA_Data(15, 0);

            // Image Buffer: Push
            Functions.IVA_PushBuffer(ivaData, image, 0);

            // Operators: NOR Image
            Algorithms.Nor(image, Functions.IVA_GetBuffer(ivaData, 0), image);

            // Extract Color Plane
            using (VisionImage plane = new VisionImage(ImageType.U8, 7))
            {
                // Extract the red color plane and copy it to the main image.
                Algorithms.ExtractColorPlanes(image, ColorMode.Rgb, plane, null, null);
                Algorithms.Copy(plane, image);
            }

            // Thresholds an image into 2 classes by using local thresholding.
            LocalThresholdOptions vaLocalThresholdOptions = new LocalThresholdOptions();

            vaLocalThresholdOptions.DeviationWeight = 1;
            vaLocalThresholdOptions.Method          = LocalThresholdMethod.BackgroundCorrection;
            vaLocalThresholdOptions.ParticleType    = ParticleType.Dark;
            vaLocalThresholdOptions.ReplaceValue    = 1;
            vaLocalThresholdOptions.WindowHeight    = 35;
            vaLocalThresholdOptions.WindowWidth     = 35;
            Algorithms.LocalThreshold(image, image, vaLocalThresholdOptions);

            // Basic Morphology - Applies morphological transformations to binary images.
            int[] vaCoefficients            = { 1, 1, 1, 1, 1, 1, 1, 1, 1 };
            StructuringElement vaStructElem = new StructuringElement(3, 3, vaCoefficients);

            vaStructElem.Shape = StructuringElementShape.Square;
            // Applies morphological transformations
            Algorithms.Morphology(image, image, MorphologyMethod.GradientOut, vaStructElem);

            // Advanced Morphology: Fill Holes
            Algorithms.FillHoles(image, image, Connectivity.Connectivity8);

            // Advanced Morphology: Remove Objects
            int[] vaCoefficients2            = { 1, 1, 1, 1, 1, 1, 1, 1, 1 };
            StructuringElement vaStructElem2 = new StructuringElement(3, 3, vaCoefficients2);

            vaStructElem.Shape = StructuringElementShape.Hexagon;
            // Filters particles based on their size.
            Algorithms.RemoveParticle(image, image, 6, SizeToKeep.KeepLarge, Connectivity.Connectivity8, vaStructElem2);

            // Advanced Morphology: Remove Border Objects - Eliminates particles touching the border of the image.
            Algorithms.RejectBorder(image, image, Connectivity.Connectivity8);

            // Lookup Table: Equalize
            // Calculates the histogram of the image and redistributes pixel values
            // accross the desired range to maintain the same pixel value distribution.
            Range equalizeRange = new Range(0, 255);

            if (image.Type != ImageType.U8)
            {
                equalizeRange.Maximum = 0;
            }
            Algorithms.Equalize(image, image, null, equalizeRange, null);

            // Image Buffer: Push
            Functions.IVA_PushBuffer(ivaData, image, 1);

            // Particle Analysis - Computes the number of particles detected in a binary image and
            // returns the requested measurements about the particles.
            Collection <MeasurementType> vaPixelMeasurements      = new Collection <MeasurementType>(new MeasurementType[] { MeasurementType.BoundingRectLeft, MeasurementType.BoundingRectTop, MeasurementType.BoundingRectRight, MeasurementType.BoundingRectBottom, MeasurementType.MaxFeretDiameter });
            Collection <MeasurementType> vaCalibratedMeasurements = new Collection <MeasurementType>(new MeasurementType[] {});

            //IVA_Particle(image, Connectivity.Connectivity4, null, null, null, 10, out vaParticleReport, out vaParticleReportCalibrated);
            IVA_Particle(image, Connectivity.Connectivity4, vaPixelMeasurements, vaCalibratedMeasurements, ivaData, 10, out vaParticleReport, out vaParticleReportCalibrated);

            // Image Buffer: Pop
            Algorithms.Copy(Functions.IVA_GetBuffer(ivaData, 1), image);

            // Creates a new, empty region of interest.
            Roi roi = new Roi();
            // Creates a new RectangleContour using the given values.
            RectangleContour vaRect = new RectangleContour(0, 0, image.Width, image.Height);

            roi.Add(vaRect);
            // Classifies all the objects located in the given ROI.
            string vaClassifierFilePath = "C:\\DATA\\#hasilscan3\\Particle Classifier.clf";

            vaClassifierReports = IVA_Classify(image, roi, vaClassifierFilePath);
            VisGrainTypeCollection colType = new VisGrainTypeCollection(vaClassifierReports);

            roi.Dispose();

            // Image Buffer: Pop
            Algorithms.Copy(Functions.IVA_GetBuffer(ivaData, 1), image);

            // Creates a new, empty region of interest.
            Roi roi2 = new Roi();
            // Creates a new RectangleContour using the given values.
            RectangleContour vaRect2 = new RectangleContour(0, 0, image.Width, image.Height);

            roi2.Add(vaRect2);
            // Classifies all the objects located in the given ROI.
            string vaClassifierFilePath2 = "C:\\DATA\\#hasilscan3\\Ukuran Classifier.clf";

            vaClassifierReports2 = IVA_Classify(image, roi2, vaClassifierFilePath2);
            VisGrainSizeCollection colSize = new VisGrainSizeCollection(vaClassifierReports2);

            GrainResults = new VisGrainDataCollection(vaClassifierReports, vaClassifierReports2, ListShape);

            roi2.Dispose();

            // Dispose the IVA_Data structure.
            ivaData.Dispose();

            // Return the palette type of the final image.
            return(PaletteType.Binary);
        }
Example #26
0
 /// <summary>
 /// Initializes a new instance of the Opening class with the
 /// given <see cref="StructuringElement"/>.
 /// </summary>
 /// <param name="se">
 /// The <see cref="StructuringElement"/> to use for opening.
 /// </param>
 public Opening (StructuringElement se)
 {
         this.se = se;
 }
 public Dilate(StructuringElement s)
 {
     structure = s;
 }
Example #28
0
 /// <summary>
 /// Initializes a new instance of the TopHat class with the
 /// given <see cref="StructuringElement"/>.
 /// </summary>
 /// <param name="se">
 /// The <see cref="StructuringElement"/> to use for top hat
 /// filtering.
 /// </param>
 public TopHat(StructuringElement se)
 {
     this.se = se;
 }
        public PaletteType ProcessImage(VisionImage image)
        {
            // Initialize the IVA_Data structure to pass results and coordinate systems.
            IVA_Data ivaData = new IVA_Data(7, 0);

            // Extract Color Plane
            using (VisionImage plane = new VisionImage(ImageType.U8, 7))
            {
                // Extract the red color plane and copy it to the main image.
                Algorithms.ExtractColorPlanes(image, ColorMode.Rgb, plane, null, null);
                Algorithms.Copy(plane, image);
            }

            // Filters: Convolution - Applies a linear filter to an image by convolving the image with a filtering kernel.
            double[] vaCoefficients = { 1, 2, 4, 2, 1, 2, 4, 8, 4, 2, 4, 8, 16, 8, 4, 2, 4, 8, 4, 2, 1, 2, 4, 2, 1 };
            Algorithms.Convolute(image, image, new Kernel(5, 5, vaCoefficients));

            // Filters: Convolution - Applies a linear filter to an image by convolving the image with a filtering kernel.
            double[] vaCoefficients2 = { -1, -1, -1, -1, 10, -1, -1, -1, -1 };
            Algorithms.Convolute(image, image, new Kernel(3, 3, vaCoefficients2));

            // Automatic Threshold
            Algorithms.AutoThreshold(image, image, 2, ThresholdMethod.Clustering);

            // Basic Morphology - Applies morphological transformations to binary images.
            int[] vaCoefficients3           = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
            StructuringElement vaStructElem = new StructuringElement(7, 7, vaCoefficients3);

            vaStructElem.Shape = StructuringElementShape.Hexagon;
            // Applies morphological transformations
            Algorithms.Morphology(image, image, MorphologyMethod.Open, vaStructElem);

            // Lookup Table: Equalize
            // Calculates the histogram of the image and redistributes pixel values
            // accross the desired range to maintain the same pixel value distribution.
            Range equalizeRange = new Range(0, 255);

            if (image.Type != ImageType.U8)
            {
                equalizeRange.Maximum = 0;
            }
            Algorithms.Equalize(image, image, null, equalizeRange, null);

            // Creates a new, empty region of interest.
            Roi roi = new Roi();
            // Creates a new RectangleContour using the given values.
            RectangleContour vaRect = new RectangleContour(0, 0, image.Width, image.Height);

            roi.Add(vaRect);
            // Classifies all the objects located in the given ROI.
            string vaClassifierFilePath = "C:\\DATA\\#hasilscan2\\Ukuran Classifier.clf";

            vaClassifierReports = IVA_Classify(image, roi, vaClassifierFilePath);

            roi.Dispose();

            // Dispose the IVA_Data structure.
            ivaData.Dispose();

            // Return the palette type of the final image.
            return(PaletteType.Binary);
        }
Example #30
0
 /// <summary>
 /// Initializes a new instance of the Dilation class with the
 /// given <see cref="StructuringElement"/>.
 /// </summary>
 /// <param name="se">
 /// The <see cref="StructuringElement"/> to use for dilation.
 /// </param>
 public Dilation(StructuringElement se)
 {
     this.se = se;
 }
Example #31
0
 /// <summary>
 /// Initializes a new instance of the TopHat class with the
 /// given <see cref="StructuringElement"/>.
 /// </summary>
 /// <param name="se">
 /// The <see cref="StructuringElement"/> to use for top hat 
 /// filtering.
 /// </param>
 public TopHat (StructuringElement se)
 {
         this.se = se;
 }
        static void Main()
        {
            var g1 = new StructuringElement(StructuringElementShape.Rectangle, 3);
            var g2 = new StructuringElement(StructuringElementShape.Rectangle, 23);
            var g3 = new StructuringElement(StructuringElementShape.Rectangle, 43);
            var g4 = new StructuringElement(StructuringElementShape.Rectangle, 63);
            var g5 = new StructuringElement(StructuringElementShape.Rectangle, 83);

            var s_c_3  = new StructuringElement(StructuringElementShape.Cross, 3);
            var s_r_3  = new StructuringElement(StructuringElementShape.Rectangle, 3);
            var s_c_5  = new StructuringElement(StructuringElementShape.Cross, 5);
            var s_r_5  = new StructuringElement(StructuringElementShape.Rectangle, 5);
            var s_c_7  = new StructuringElement(StructuringElementShape.Cross, 7);
            var s_r_7  = new StructuringElement(StructuringElementShape.Rectangle, 7);
            var s_c_9  = new StructuringElement(StructuringElementShape.Cross, 9);
            var s_r_9  = new StructuringElement(StructuringElementShape.Rectangle, 9);
            var s_r_11 = new StructuringElement(StructuringElementShape.Rectangle, 11);
            var ops    = new IImageOperation[]
            {
                new Complement(),
                new Threshold(63),
                new Threshold(127),
                new Threshold(191),
                new BandFilter(63, 191),
                new NotchFilter(63, 191),
                new BandFilter(181, 201),
                new NotchFilter(181, 201),
                new Mask(new NotchFilter(63, 191)),
                new Dilate(s_r_3),
                new Dilate(s_r_5),
                new Dilate(s_r_7),
                new Dilate(s_r_9),
                new Dilate(s_r_11),
                new Open(g1),
                new Open(g2),
                new Open(g3),
                new Open(g4),
                new Open(g5),
                new BoundaryTrace(s_c_3),
                new BoundaryTrace(s_r_3),
                new BoundaryTrace(s_c_5),
                new BoundaryTrace(s_r_5),
                new BoundaryTrace(s_c_7),
                new BoundaryTrace(s_r_7),
                new BoundaryTrace(s_c_9),
                new BoundaryTrace(s_r_9),
                new OpenClose(s_c_3),
                new OpenClose(s_r_3),
                new OpenClose(s_c_5),
                new OpenClose(s_r_5),
                new OpenClose(s_c_7),
                new OpenClose(s_r_7),
                new OpenClose(s_c_9),
                new OpenClose(s_r_9),
                new CloseOpen(s_c_3),
                new CloseOpen(s_r_3),
                new CloseOpen(s_c_5),
                new CloseOpen(s_r_5),
                new CloseOpen(s_c_7),
                new CloseOpen(s_r_7),
                new CloseOpen(s_c_9),
                new CloseOpen(s_r_9),
                new ImageX(),
                new ImageY(),
                new ImageZ(),
            };

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new INFOIBV(ops));
        }
Example #33
0
 /// <summary>
 /// Initializes a new instance of the Closing class with the
 /// given <see cref="StructuringElement"/>.
 /// </summary>
 /// <param name="se">
 /// The <see cref="StructuringElement"/> to use for closing.
 /// </param>
 public BottomHat (StructuringElement se)
 {
         this.se = se;
 }
Example #34
0
 /// <summary>
 /// Initializes a new instance of the Erosion class with the
 /// given <see cref="StructuringElement"/>.
 /// </summary>
 /// <param name="se">
 /// The <see cref="StructuringElement"/> to use for erosion.
 /// </param>
 public Erosion(StructuringElement se)
 {
     this.se = se;
 }
Example #35
0
 /// <summary>
 /// Initializes a new instance of the Closing class with the
 /// given <see cref="StructuringElement"/>.
 /// </summary>
 /// <param name="se">
 /// The <see cref="StructuringElement"/> to use for closing.
 /// </param>
 public Closing (StructuringElement se)
 {
         this.se = se;
 }
Example #36
0
 /// <summary>
 /// Initializes a new instance of the Opening class with the
 /// given <see cref="StructuringElement"/>.
 /// </summary>
 /// <param name="se">
 /// The <see cref="StructuringElement"/> to use for opening.
 /// </param>
 public Opening(StructuringElement se)
 {
     this.se = se;
 }