public PolygonSubType CheckPolygonSubType(List <IntPoint> corners) { PolygonSubType polygonSubType = PolygonSubType.Unknown; PointsCloud.GetBoundingRectangle(corners, out IntPoint minXY, out IntPoint maxXY); IntPoint intPoint = maxXY - minXY; float num = lengthError * (float)(intPoint.X + intPoint.Y) / 2f; if (corners.Count == 3) { float angleBetweenVectors = GeometryTools.GetAngleBetweenVectors(corners[0], corners[1], corners[2]); float angleBetweenVectors2 = GeometryTools.GetAngleBetweenVectors(corners[1], corners[2], corners[0]); float angleBetweenVectors3 = GeometryTools.GetAngleBetweenVectors(corners[2], corners[0], corners[1]); if (System.Math.Abs(angleBetweenVectors - 60f) <= angleError && System.Math.Abs(angleBetweenVectors2 - 60f) <= angleError && System.Math.Abs(angleBetweenVectors3 - 60f) <= angleError) { polygonSubType = PolygonSubType.EquilateralTriangle; } else { if (System.Math.Abs(angleBetweenVectors - angleBetweenVectors2) <= angleError || System.Math.Abs(angleBetweenVectors2 - angleBetweenVectors3) <= angleError || System.Math.Abs(angleBetweenVectors3 - angleBetweenVectors) <= angleError) { polygonSubType = PolygonSubType.IsoscelesTriangle; } if (System.Math.Abs(angleBetweenVectors - 90f) <= angleError || System.Math.Abs(angleBetweenVectors2 - 90f) <= angleError || System.Math.Abs(angleBetweenVectors3 - 90f) <= angleError) { polygonSubType = ((polygonSubType == PolygonSubType.IsoscelesTriangle) ? PolygonSubType.RectangledIsoscelesTriangle : PolygonSubType.RectangledTriangle); } } } else if (corners.Count == 4) { float angleBetweenLines = GeometryTools.GetAngleBetweenLines(corners[0], corners[1], corners[2], corners[3]); float angleBetweenLines2 = GeometryTools.GetAngleBetweenLines(corners[1], corners[2], corners[3], corners[0]); if (angleBetweenLines <= angleError) { polygonSubType = PolygonSubType.Trapezoid; if (angleBetweenLines2 <= angleError) { polygonSubType = PolygonSubType.Parallelogram; if (System.Math.Abs(GeometryTools.GetAngleBetweenVectors(corners[1], corners[0], corners[2]) - 90f) <= angleError) { polygonSubType = PolygonSubType.Rectangle; } float num2 = corners[0].DistanceTo(corners[1]); float num3 = corners[0].DistanceTo(corners[3]); if (System.Math.Abs(num2 - num3) <= num) { polygonSubType = ((polygonSubType == PolygonSubType.Parallelogram) ? PolygonSubType.Rhombus : PolygonSubType.Square); } } } else if (angleBetweenLines2 <= angleError) { polygonSubType = PolygonSubType.Trapezoid; } } return(polygonSubType); }
private void checkShape(SimpleShapeChecker shapeChecker, List <IntPoint> edgePts) { AForge.Point center; float radius; List <IntPoint> corners; if (edgePts.Count > 4 && shapeChecker.IsCircle(edgePts, out center, out radius)) { //shape is a circle drawEllipse(center, radius); shapeCount[0]++; } else if (edgePts.Count > 3 && shapeChecker.IsConvexPolygon(edgePts, out corners)) { PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); if (subType == PolygonSubType.Unknown) { shapeCount[4]++; } else if (subType == PolygonSubType.Square) { shapeCount[2]++; } else if (subType == PolygonSubType.Rectangle) { shapeCount[3]++; } else if (subType == PolygonSubType.Trapezoid) { shapeCount[5]++; } else if (subType == PolygonSubType.EquilateralTriangle) { shapeCount[1]++; } else if (subType == PolygonSubType.IsoscelesTriangle) { shapeCount[1]++; } drawPolygon(corners); } else if (shapeChecker.IsTriangle(edgePts)) { //triangle shapeCount[1]++; } }
public static Bitmap buscaRectangulos(Bitmap bitmap) { Blob[] blobs; Rectangle area = new Rectangle(0, 0, bitmap.Width, bitmap.Height); // lock image BitmapData bitmapData = bitmap.LockBits(area, ImageLockMode.ReadWrite, bitmap.PixelFormat); // Filtramos la imagen para determinar hasts cuando de ROJO, VERDE Y AZUL se permitiráanalizar ColorFiltering colorFilter = new ColorFiltering(); colorFilter.Red = new IntRange(0, 104); colorFilter.Green = new IntRange(0, 104); colorFilter.Blue = new IntRange(0, 104); colorFilter.FillOutsideRange = false; colorFilter.ApplyInPlace(bitmapData); // Localizamos objetos en la imagen BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = 15; blobCounter.MinWidth = 15; blobCounter.ProcessImage(bitmapData); blobs = blobCounter.GetObjectsInformation(); bitmap.UnlockBits(bitmapData); // step 3 -check objects' type and highlight SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); Graphics g = Graphics.FromImage(bitmap); Pen yellowPen = new Pen(Color.Yellow, 2); // Para cada figuura encontrada for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); List <IntPoint> corners; // Cuadrado if (shapeChecker.IsQuadrilateral(edgePoints, out corners)) {//Obtenemos cuantas esquinas tiene el shape PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); //Pintamos las áreas detectadas areaInteres(g, corners); } } //yellowPen.Dispose(); g.Dispose(); // put new image to clipboard Clipboard.SetDataObject(bitmap); // and to picture box return(bitmap); }
[TestCase( PolygonSubType.Unknown, new int[] { 0, 0, 100, 0, 90, 50, 40, 70, 10, 40 } )] // unknown if 5 corners or more public void CheckPolygonSubTypeTest( PolygonSubType expectedSubType, int[] corners ) { Assert.AreEqual( expectedSubType, shapeChecker.CheckPolygonSubType( GetListOfPointFromArray( corners ) ) ); }
/// <summary> /// Check sub type of a convex polygon. /// </summary> /// /// <param name="corners">Corners of the convex polygon to check.</param> /// /// <returns>Return detected sub type of the specified shape.</returns> /// /// <remarks><para>The method check corners of a convex polygon detecting /// its subtype. Polygon's corners are usually retrieved using <see cref="IsConvexPolygon"/> /// method, but can be any list of 3-4 points (only sub types of triangles and /// quadrilateral are checked).</para> /// /// <para>See <see cref="AngleError"/> and <see cref="LengthError"/> properties, /// which set acceptable errors for polygon sub type checking.</para> /// </remarks> /// public PolygonSubType CheckPolygonSubType(List <IntPoint> corners) { PolygonSubType subType = PolygonSubType.Unknown; // get bounding rectangle of the points list IntPoint minXY, maxXY; PointsCloud.GetBoundingRectangle(corners, out minXY, out maxXY); // get cloud's size IntPoint cloudSize = maxXY - minXY; float maxLengthDiff = lengthError * (cloudSize.X + cloudSize.Y) / 2; if (corners.Count == 3) { // get angles of the triangle float angle1 = GeometryTools.GetAngleBetweenVectors(IntPoint.ToPoint(corners[0]), IntPoint.ToPoint(corners[1]), IntPoint.ToPoint(corners[2])); float angle2 = GeometryTools.GetAngleBetweenVectors(IntPoint.ToPoint(corners[1]), IntPoint.ToPoint(corners[2]), IntPoint.ToPoint(corners[0])); float angle3 = GeometryTools.GetAngleBetweenVectors(IntPoint.ToPoint(corners[2]), IntPoint.ToPoint(corners[0]), IntPoint.ToPoint(corners[1])); // check for equilateral triangle if ((Math.Abs(angle1 - 60) <= angleError) && (Math.Abs(angle2 - 60) <= angleError) && (Math.Abs(angle3 - 60) <= angleError)) { subType = PolygonSubType.EquilateralTriangle; } else { // check for isosceles triangle if ((Math.Abs(angle1 - angle2) <= angleError) || (Math.Abs(angle2 - angle3) <= angleError) || (Math.Abs(angle3 - angle1) <= angleError)) { subType = PolygonSubType.IsoscelesTriangle; } // check for rectangled triangle if ((Math.Abs(angle1 - 90) <= angleError) || (Math.Abs(angle2 - 90) <= angleError) || (Math.Abs(angle3 - 90) <= angleError)) { subType = (subType == PolygonSubType.IsoscelesTriangle) ? PolygonSubType.RectangledIsoscelesTriangle : PolygonSubType.RectangledTriangle; } } } else if (corners.Count == 4) { // get angles between 2 pairs of opposite sides float angleBetween1stPair = GeometryTools.GetAngleBetweenLines(IntPoint.ToPoint(corners[0]), IntPoint.ToPoint(corners[1]), IntPoint.ToPoint(corners[2]), IntPoint.ToPoint(corners[3])); float angleBetween2ndPair = GeometryTools.GetAngleBetweenLines(IntPoint.ToPoint(corners[1]), IntPoint.ToPoint(corners[2]), IntPoint.ToPoint(corners[3]), IntPoint.ToPoint(corners[0])); // check 1st pair for parallelism if (angleBetween1stPair <= angleError) { subType = PolygonSubType.Trapezoid; // check 2nd pair for parallelism if (angleBetween2ndPair <= angleError) { subType = PolygonSubType.Parallelogram; // check angle between adjacent sides if (Math.Abs(GeometryTools.GetAngleBetweenVectors(IntPoint.ToPoint(corners[1]), IntPoint.ToPoint(corners[0]), IntPoint.ToPoint(corners[2])) - 90) <= angleError) { subType = PolygonSubType.Rectangle; } // get length of 2 adjacent sides float side1Length = (float)corners[0].DistanceTo(corners[1]); float side2Length = (float)corners[0].DistanceTo(corners[3]); if (Math.Abs(side1Length - side2Length) <= maxLengthDiff) { subType = (subType == PolygonSubType.Parallelogram) ? PolygonSubType.Rhombus : PolygonSubType.Square; } } } else { // check 2nd pair for parallelism - last chence to detect trapezoid if (angleBetween2ndPair <= angleError) { subType = PolygonSubType.Trapezoid; } } } return(subType); }
private void ProcessImage(Bitmap bitmap) { if (CBApplyCanny.Checked) { Bitmap video2 = (Bitmap)bitmap.Clone(); Grayscale gray = new Grayscale(0.2125, 0.7154, 0.0721); Bitmap video3 = gray.Apply(video2); CannyEdgeDetector canny = new CannyEdgeDetector(0, 70); canny.ApplyInPlace(video3); //PictureViewerEditor.Image = (Bitmap)Image.FromFile(imageFileName); PBCanny.Image = (Bitmap)video3.Clone();//assign the pointer back to the clone //if (CBFindCircles.Checked) //{ // //System.Drawing.Image returnImage = null; // //returnImage = (System.Drawing.Image)CaptureBox.Image.Clone(); // // Clipboard.SetImage(replacementImage); // Bitmap cannyImage = (Bitmap)PBCapture.Image.Clone(); // ProcessImage(cannyImage); // return; //} GC.Collect(); //return; } // lock image BitmapData bitmapData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); // step 1 - turn background to black ColorFiltering colorFilter = new ColorFiltering(); colorFilter.Red = new IntRange(0, 64); colorFilter.Green = new IntRange(0, 64); colorFilter.Blue = new IntRange(0, 64); colorFilter.FillOutsideRange = false; colorFilter.ApplyInPlace(bitmapData); // step 2 - locating objects BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = 5; blobCounter.MinWidth = 5; blobCounter.ProcessImage(bitmapData); Blob[] blobs = blobCounter.GetObjectsInformation(); bitmap.UnlockBits(bitmapData); PBCanny.Image = (Bitmap)bitmap.Clone(); // step 3 - check objects' type and highlight SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); Graphics g = Graphics.FromImage(bitmap); Pen yellowPen = new Pen(Color.Yellow, 2); // circles Pen redPen = new Pen(Color.Red, 2); // quadrilateral Pen brownPen = new Pen(Color.Brown, 2); // quadrilateral with known sub-type Pen greenPen = new Pen(Color.Green, 2); // known triangle Pen bluePen = new Pen(Color.Blue, 2); // triangle for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); AForge.Point center; float radius; // is circle ? if (shapeChecker.IsCircle(edgePoints, out center, out radius)) { g.DrawEllipse(yellowPen, (float)(center.X - radius), (float)(center.Y - radius), (float)(radius * 2), (float)(radius * 2)); } else { List <IntPoint> corners; // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { // get sub-type PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); Pen pen; if (subType == PolygonSubType.Unknown) { pen = (corners.Count == 4) ? redPen : bluePen; } else { pen = (corners.Count == 4) ? brownPen : greenPen; } g.DrawPolygon(pen, ToPointsArray(corners)); } } } yellowPen.Dispose(); redPen.Dispose(); greenPen.Dispose(); bluePen.Dispose(); brownPen.Dispose(); g.Dispose(); // put new image to clipboard //Clipboard.SetDataObject(bitmap); // and to picture box PBAnalysis.Image = bitmap; //UpdatePictureBoxPosition(); }
// Process image private void ProcessImage(Bitmap bitmap) { // lock image BitmapData bitmapData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); // step 1 - turn background to black ColorFiltering colorFilter = new ColorFiltering { Blue = new IntRange(0, 64), FillOutsideRange = false }; colorFilter.ApplyInPlace(bitmapData); // step 2 - locating objects BlobCounter blobCounter = new BlobCounter { FilterBlobs = true, MinHeight = 5, MinWidth = 5 }; blobCounter.ProcessImage(bitmapData); Blob[] blobs = blobCounter.GetObjectsInformation(); bitmap.UnlockBits(bitmapData); // step 3 - check objects' type and highlight SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); //Pen colorPen = new Pen(Color.Yellow, 2); // quadrilateral with known sub-type using (Graphics g = Graphics.FromImage(bitmap)) // SourceImage is a Bitmap object { for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out List <IntPoint> corners)) { // get sub-type PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); if (subType != PolygonSubType.Unknown) { if (corners.Count == 4) { // ignore the application window itself if (corners[0].X <= 15) { continue; } else { //g.DrawPolygon(colorPen, ToPointsArray(corners)); int right = corners[0].X, left = corners[0].X, top = corners[0].Y, bottom = corners[0].Y; for (int j = 0; j < corners.Count; j++) { if (corners[j].X > right) { right = corners[j].X; } if (corners[j].X < left) { left = corners[j].X; } if (corners[j].Y > bottom) { bottom = corners[j].Y; } if (corners[j].Y < top) { top = corners[j].Y; } } Rectangle section = new Rectangle(new System.Drawing.Point(left, top), new Size(right - left, bottom - top)); IntPoint center = new IntPoint(((right - left) / 2) + left, ((top - bottom) / 2) + top); grid.Add(DetectStatus(CropImage(bitmap, section), center, section)); } } } } } } //colorPen.Dispose(); //sweeperGrid[10].Save(@".\image2.png"); // put new image to clipboard //bitmap.Save(@".\image.png"); }
//private List<Triangle> LoadImage() //{ // // load arrow bitmap // string embeddedFileName = CheckForUploadedFile(); // Assembly assembly = this.GetType().Assembly; // Bitmap image = new Bitmap(assembly.GetManifestResourceStream(embeddedFileName)); // List<Triangle> triangleList; // // triangleList= ProcessImage(image); // return triangleList; //} private List <Triangle> ProcessImage() { List <Triangle> TriangleList = new List <Triangle>(); List <ULBounds> triBounds = new List <ULBounds>(); int currentMaxX = 0; int currentMaxY = 0; int currentUBoundsX = 0; int currentUBoundsY = 0; int currentCol = 0; String currentRow = String.Empty; string embeddedFileName = CheckForUploadedFile(); if (embeddedFileName == String.Empty) { TriangleList = NoTriangleFound(); return(TriangleList); } Bitmap bitmap = (Bitmap)Bitmap.FromFile(embeddedFileName); // Triangle Class List // values needed to find area of a triangle // double[] X; // double[] Y; int z; double area; // lock image String filePath = CheckForUploadedFile(); Int16 Tol = 38; Color replace1 = new Color(); replace1 = Color.FromArgb(129, 187, 237); Color newColor = new Color(); newColor = Color.FromArgb(0, 0, 0); ImageConverter ic = new ImageConverter(); Color replace2 = new Color(); replace2 = Color.FromArgb(199, 221, 234); Tol = 38; System.Drawing.Image tmpImage = System.Drawing.Image.FromFile(filePath); tmpImage = ColorReplace(tmpImage, Tol, replace1, newColor); ColorReplace(tmpImage, Tol, replace2, newColor); // UpdatePictureBoxPositionOutPut(); bitmap = new Bitmap(tmpImage); BitmapData bitmapData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); // step 1 - turn background to black ColorFiltering colorFilter = new ColorFiltering(); colorFilter.Red = new IntRange(0, 64); colorFilter.Green = new IntRange(0, 64); colorFilter.Blue = new IntRange(0, 64); colorFilter.FillOutsideRange = false; colorFilter.ApplyInPlace(bitmapData); // step 2 - locating objects BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = 5; blobCounter.MinWidth = 5; blobCounter.ProcessImage(bitmapData); Blob[] blobs = blobCounter.GetObjectsInformation(); bitmap.UnlockBits(bitmapData); // step 3 - check objects' type and highlight SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); Graphics g = Graphics.FromImage(bitmap); Pen yellowPen = new Pen(Color.Yellow, 2); // circles Pen redPen = new Pen(Color.Red, 2); // quadrilateral Pen brownPen = new Pen(Color.Brown, 2); // quadrilateral with known sub-type Pen greenPen = new Pen(Color.Green, 2); // known triangle Pen bluePen = new Pen(Color.Blue, 2); // triangle int triFound = 0; for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); DoublePoint center; double radius; int tempX = 0; int tempY = 0; int tempCol = 0; String tempRow = string.Empty; // is circle ? if (shapeChecker.IsCircle(edgePoints, out center, out radius)) { g.DrawEllipse(yellowPen, (float)(center.X - radius), (float)(center.Y - radius), (float)(radius * 2), (float)(radius * 2)); } else { List <IntPoint> corners; // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { // get sub-type PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); Pen pen; if (subType == PolygonSubType.Unknown) { pen = (corners.Count == 4) ? redPen : bluePen; } else { pen = (corners.Count == 4) ? brownPen : yellowPen; double[] X = { corners[0].X, corners[1].X, corners[2].X }; double[] Y = { corners[0].Y, corners[1].Y, corners[2].Y }; z = X.Length; area = polygonArea(X, Y, z); if (area < 40000) { triFound = triFound + 1; Triangle tmpTri = new Triangle(); ULBounds tmpULB = new ULBounds(); tmpTri.Name = "Triangle " + triFound.ToString(); tmpTri.PtAx = corners[0].X; tmpTri.PtAy = corners[0].Y; if (tmpTri.PtAx > currentMaxX) { currentMaxX = tmpTri.PtAx; } if (tmpTri.PtAy > currentMaxY) { currentMaxY = tmpTri.PtAy; } tmpTri.PtBx = corners[1].X; tmpTri.PtBy = corners[1].Y; if (tmpTri.PtBx > currentMaxX) { currentMaxX = tmpTri.PtBx; } if (tmpTri.PtBy > currentMaxY) { currentMaxY = tmpTri.PtBy; } tmpTri.PtCx = corners[2].X; tmpTri.PtCy = corners[2].Y; if (tmpTri.PtCx > currentMaxX) { currentMaxX = tmpTri.PtCx; } if (tmpTri.PtBy > currentMaxY) { currentMaxY = tmpTri.PtBy; } if (currentCol == 0) { currentCol++; tempCol = currentCol; currentUBoundsY = currentMaxY; } else { currentCol = GetMaxColumn(triBounds); } if (currentRow == string.Empty) { currentRow = Increment(currentRow); tempRow = currentRow; currentUBoundsX = currentMaxX; } else { currentRow = GetMaxRow(triBounds); }; if (triBounds.Count == 0) { //adding Row tmpULB.Col = 0; tmpULB.Row = tempRow; tmpULB.Lower = 0; tmpULB.Upper = currentMaxY; triBounds.Add(tmpULB); tmpULB = new ULBounds(); //adding Col tmpULB.Col = tempCol; tmpULB.Row = String.Empty; tmpULB.Lower = 0; tmpULB.Upper = currentMaxX; triBounds.Add(tmpULB); } if (currentMaxX > (currentUBoundsX * 1.15)) { currentUBoundsX = GetMaxColumnUBounds(triBounds); if (currentMaxX > (currentUBoundsX * 1.15)) { tempCol = GetMaxColumn(triBounds); tmpULB = new ULBounds(); tempCol = tempCol++; tmpULB.Col = tempCol; tmpULB.Row = String.Empty; tmpULB.Lower = currentUBoundsX + 1; tmpULB.Upper = currentMaxX; triBounds.Add(tmpULB); } } if (currentMaxY > (currentUBoundsY * 1.15)) { currentUBoundsY = GetMaxColumnUBounds(triBounds); if (currentMaxY > (currentUBoundsY * 1.15)) { tempRow = GetMaxRow(triBounds); tmpULB = new ULBounds(); tempRow = Increment(tempRow); //adding Col tmpULB.Col = tempCol; tmpULB.Row = String.Empty; tmpULB.Lower = 0; tmpULB.Upper = currentMaxX; triBounds.Add(tmpULB); } } tmpTri.Row = currentRow.ToUpper(); tmpTri.Col = currentCol; tmpTri.Area = polygonArea(X, Y, z); TriangleList.Add(tmpTri); } } g.DrawPolygon(pen, ToPointsArray(corners)); } } } yellowPen.Dispose(); redPen.Dispose(); greenPen.Dispose(); bluePen.Dispose(); brownPen.Dispose(); g.Dispose(); return(TriangleList); }
// Process image void ProcessImage(Bitmap bitmap) { #if !SILVERLIGHT && !UNITY_WEBPLAYER // lock image BitmapData bitmapData = bitmap.LockBits( new RectI(0, 0, bitmap.PixelWidth, bitmap.PixelHeight), ImageLockMode.ReadWrite, bitmap.PixelFormat); // step 1 - turn background to black ColorFiltering colorFilter = new ColorFiltering(); colorFilter.Red = new IntRange(0, 64); colorFilter.Green = new IntRange(0, 64); colorFilter.Blue = new IntRange(0, 64); colorFilter.FillOutsideRange = false; colorFilter.ApplyInPlace(bitmapData); // step 2 - locating objects BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = 5; blobCounter.MinWidth = 5; blobCounter.ProcessImage(bitmapData); Blob[] blobs = blobCounter.GetObjectsInformation(); bitmap.UnlockBits(bitmapData); // step 3 - check objects' type and highlight SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); Graphics g = Graphics.FromImage(bitmap); Pen yellowPen = new Pen(Color.Yellow, 2); // circles Pen redPen = new Pen(Color.Red, 2); // quadrilateral Pen brownPen = new Pen(Color.Brown, 2); // quadrilateral with known sub-type Pen greenPen = new Pen(Color.Green, 2); // known triangle Pen bluePen = new Pen(Color.Blue, 2); // triangle for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); global::AForge.Point center; float radius; // is circle ? if (shapeChecker.IsCircle(edgePoints, out center, out radius)) { g.DrawEllipse(yellowPen, (float)(center.X - radius), (float)(center.Y - radius), (float)(radius * 2), (float)(radius * 2)); } else { List <IntPoint> corners; // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { // get sub-type PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); Pen pen; if (subType == PolygonSubType.Unknown) { pen = (corners.Count == 4) ? redPen : bluePen; } else { pen = (corners.Count == 4) ? brownPen : greenPen; } g.DrawPolygon(pen, ToPointsArray(corners)); } } } yellowPen.Dispose(); redPen.Dispose(); greenPen.Dispose(); bluePen.Dispose(); brownPen.Dispose(); g.Dispose(); #endif // and to picture box pictureBox.Image = bitmap; }
public bool markKnownForms() { if (currentImage != null) { try { Bitmap image = new Bitmap(this.currentImage); // lock image BitmapData bmData = image.LockBits( new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, image.PixelFormat); // turn background to black ColorFiltering cFilter = new ColorFiltering { Red = new IntRange(0, 64), Green = new IntRange(0, 64), Blue = new IntRange(0, 64), FillOutsideRange = false }; cFilter.ApplyInPlace(bmData); // locate objects BlobCounter bCounter = new BlobCounter { FilterBlobs = true, MinHeight = 10, MinWidth = 10 }; bCounter.ProcessImage(bmData); Blob[] baBlobs = bCounter.GetObjectsInformation(); image.UnlockBits(bmData); // coloring objects SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); Graphics g = Graphics.FromImage(image); Pen yellowPen = new Pen(Color.Yellow, 2); // circles Pen redPen = new Pen(Color.Red, 2); // quadrilateral Pen brownPen = new Pen(Color.Brown, 2); // quadrilateral with known sub-type Pen greenPen = new Pen(Color.Green, 2); // known triangle Pen bluePen = new Pen(Color.Blue, 2); // triangle for (int i = 0, n = baBlobs.Length; i < n; i++) { List <IntPoint> edgePoints = bCounter.GetBlobsEdgePoints(baBlobs[i]); // is circle ? if (shapeChecker.IsCircle(edgePoints, out AForge.Point center, out float radius)) { //g.DrawEllipse(yellowPen, // (float)(center.X - radius), (float)(center.Y - radius), // (float)(radius * 2), (float)(radius * 2)); g.DrawEllipse(yellowPen, (float)(center.X - radius), (float)(center.Y - radius), (float)(radius * 2), (float)(radius * 2)); } else { if (shapeChecker.IsQuadrilateral(edgePoints, out List <IntPoint> corners)) { Rectangle[] _rects = bCounter.GetObjectsRectangles(); System.Drawing.Point[] _coordinates = ToPointsArray(corners); Pen _pen = new Pen(Color.Pink, 5); int _x = _coordinates[0].X; int _y = _coordinates[0].Y; g.DrawPolygon(_pen, ToPointsArray(corners)); } // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); Pen pen; if (subType == PolygonSubType.Unknown) { pen = (corners.Count == 4) ? redPen : bluePen; } else { pen = (corners.Count == 4) ? brownPen : greenPen; } g.DrawPolygon(pen, ToPointsArray(corners)); } } }
private void detectQuads(Bitmap bitmap) { // Greyscale filteredBitmap = Grayscale.CommonAlgorithms.BT709.Apply(bitmap); // edge filter SobelEdgeDetector edgeFilter = new SobelEdgeDetector(); edgeFilter.ApplyInPlace(filteredBitmap); // Threshhold filter Threshold threshholdFilter = new Threshold(190); threshholdFilter.ApplyInPlace(filteredBitmap); BitmapData bitmapData = filteredBitmap.LockBits( new Rectangle(0, 0, filteredBitmap.Width, filteredBitmap.Height), ImageLockMode.ReadWrite, filteredBitmap.PixelFormat); BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = 125; blobCounter.MinWidth = 125; blobCounter.ProcessImage(bitmapData); Blob[] blobs = blobCounter.GetObjectsInformation(); filteredBitmap.UnlockBits(bitmapData); SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); Bitmap bm = new Bitmap(filteredBitmap.Width, filteredBitmap.Height, PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(bm); g.DrawImage(filteredBitmap, 0, 0); Pen pen = new Pen(Color.Red, 5); List <IntPoint> cardPositions = new List <IntPoint>(); // Loop through detected shapes for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); List <IntPoint> corners; bool sameCard = false; // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { // get sub-type PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); // Only return 4 corner rectanges if ((subType == PolygonSubType.Parallelogram || subType == PolygonSubType.Rectangle) && corners.Count == 4) { // Check if its sideways, if so rearrange the corners so it's veritcal rearrangeCorners(corners); // Prevent it from detecting the same card twice foreach (IntPoint point in cardPositions) { if (corners[0].DistanceTo(point) < 40) { sameCard = true; } } if (sameCard) { continue; } // Hack to prevent it from detecting smaller sections of the card instead of the whole card if (GetArea(corners) < 20000) { continue; } cardPositions.Add(corners[0]); g.DrawPolygon(pen, ToPointsArray(corners)); // Extract the card bitmap QuadrilateralTransformation transformFilter = new QuadrilateralTransformation(corners, 211, 298); cardBitmap = transformFilter.Apply(cameraBitmap); List <IntPoint> artCorners = new List <IntPoint>(); artCorners.Add(new IntPoint(14, 35)); artCorners.Add(new IntPoint(193, 35)); artCorners.Add(new IntPoint(193, 168)); artCorners.Add(new IntPoint(14, 168)); // Extract the art bitmap QuadrilateralTransformation cartArtFilter = new QuadrilateralTransformation(artCorners, 183, 133); cardArtBitmap = cartArtFilter.Apply(cardBitmap); MagicCard card = new MagicCard(); card.corners = corners; card.cardBitmap = cardBitmap; card.cardArtBitmap = cardArtBitmap; magicCards.Add(card); } } } pen.Dispose(); g.Dispose(); filteredBitmap = bm; }
// Process image private void ProcessImage(string fileName) { Bitmap bitmap = new Bitmap(fileName); // lock image BitmapData bitmapData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); // step 1 - turn background to black ColorFiltering colorFilter = new ColorFiltering(); colorFilter.Red = new IntRange(0, 254); colorFilter.Green = new IntRange(0, 254); colorFilter.Blue = new IntRange(0, 254); colorFilter.FillOutsideRange = false; colorFilter.ApplyInPlace(bitmapData); // step 2 - locating objects BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = 5; blobCounter.MinWidth = 5; blobCounter.ProcessImage(bitmapData); Blob[] blobs = blobCounter.GetObjectsInformation(); bitmap.UnlockBits(bitmapData); // step 3 - check objects' type and highlight SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); Graphics g = Graphics.FromImage(bitmap); Pen yellowPen = new Pen(Color.Yellow, 2); // circles Pen redPen = new Pen(Color.Red, 2); // quadrilateral Pen brownPen = new Pen(Color.Brown, 2); // quadrilateral with known sub-type Pen greenPen = new Pen(Color.Green, 2); // known triangle Pen bluePen = new Pen(Color.Blue, 2); // triangle int count = 0; for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); DoublePoint center; double radius; // is circle ? if (shapeChecker.IsCircle(edgePoints, out center, out radius)) { g.DrawEllipse(yellowPen, (float)(center.X - radius), (float)(center.Y - radius), (float)(radius * 2), (float)(radius * 2)); redPointF = new PointF((float)(center.X + 320), (float)(center.Y + 60)); lblPoint.Text = string.Format("[{0}, {1}]", redPointF.X, redPointF.Y); count++; } else { List <IntPoint> corners; // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { // get sub-type PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); Pen pen; if (subType == PolygonSubType.Unknown) { pen = (corners.Count == 4) ? redPen : bluePen; } else { pen = (corners.Count == 4) ? brownPen : greenPen; } g.DrawPolygon(pen, ToPointsArray(corners)); } } } yellowPen.Dispose(); redPen.Dispose(); greenPen.Dispose(); bluePen.Dispose(); brownPen.Dispose(); g.Dispose(); // put new image to clipboard //Clipboard.SetDataObject(bitmap); // and to picture box pictureBox.Image = bitmap; if (count == 1) { string name = Path.GetFileNameWithoutExtension(fileName); var names = name.Split('_'); if (names.Length == 9) { var x = names[7]; var y = names[8]; txtXPoint.Text = x; txtYPoint.Text = y; btnCalculate_Click(null, null); } else { txtXPoint.Text = ""; txtYPoint.Text = ""; this.lblDistance.Text = ""; } } else { if (MessageBox.Show("光斑识别失败,请打开包含正常光斑的图片。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK) { this.lblPoint.Text = "[0, 0]"; txtXPoint.Text = ""; txtYPoint.Text = ""; this.lblDistance.Text = ""; this.pictureBox.Image = null; } } }
[TestCase(PolygonSubType.Unknown, new int[] { 0, 0, 100, 0, 90, 50, 40, 70, 10, 40 })] // unknown if 5 corners or more public void CheckPolygonSubTypeTest(PolygonSubType expectedSubType, int[] corners) { Assert.AreEqual(expectedSubType, shapeChecker.CheckPolygonSubType(GetListOfPointFromArray(corners))); }
// Summary - Gets the exterior rectangles. /*************** * It uses a different JPEG altogether due to bpp issue (only 24 or 32 is acceptable). * Selects the rectangles on the basis of area (around 350 to 400). * Sends the quadrilaterals (4 of them) with their 4 coordinates (each) to DecideCorners for trimming. */ public void PreProcess() { Bitmap bitmap = this.scanned_image; List <List <IntPoint> > QuadCorners = new List <List <IntPoint> >(4); BitmapData bitmapData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); // step 1 - turn background to black ColorFiltering colorFilter = new ColorFiltering(); colorFilter.Red = new IntRange(0, 64); colorFilter.Green = new IntRange(0, 64); colorFilter.Blue = new IntRange(0, 64); colorFilter.FillOutsideRange = false; //MessageBox.Show(bitmapData.PixelFormat.ToString()); colorFilter.ApplyInPlace(bitmapData); // step 2 - locating objects BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = 5; blobCounter.MinWidth = 5; blobCounter.ProcessImage(bitmapData); Blob[] blobs = blobCounter.GetObjectsInformation(); bitmap.UnlockBits(bitmapData); // step 3 - check objects' type and highlight SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); //int count = 0; Pen redPen = new Pen(Color.Red, 2); Graphics g = Graphics.FromImage(bitmap); // Threshold area values for rectangles. It doesnt have a specific equation for the value based on threshold. // Values have been tested and set accordingly. int area_upper = 0, area_lower = 0; if (Scanner_DPI.dpi_value == 200) { area_lower = 2000; area_upper = 3000; } else if (Scanner_DPI.dpi_value == 300) { area_lower = 5000; area_upper = 6000; } for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); List <IntPoint> corners; // is quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { // get sub-type PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); if (subType == PolygonSubType.Rectangle && blobs[i].Area > area_lower && blobs[i].Area < area_upper) { //g.DrawPolygon(redPen, ToPointsArray(corners)); QuadCorners.Add(corners); } } } this.scanned_image = DecideCorners(QuadCorners); }
public static Tuple <Bitmap, Bitmap, Bitmap, Bitmap, List <Bitmap> > blob(Bitmap img, Interval w, Interval h, Boolean couple) { Bitmap sourceImage = (Bitmap)(img); //////////////////////////////////////////////////// BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = (int)h.Min; blobCounter.MaxHeight = (int)h.Max; blobCounter.MinWidth = (int)w.Min; blobCounter.MaxWidth = (int)w.Max; blobCounter.CoupledSizeFiltering = couple; //blobCounter.BackgroundThreshold. blobCounter.ProcessImage(sourceImage); Blob[] blobs = blobCounter.GetObjectsInformation(); //bitmap.UnlockBits(sourceImage); //////////////////////////////////////////////////// Bitmap newBlobImg = (Bitmap)(sourceImage).Clone(); // create filter BlobsFiltering filterBlob = new BlobsFiltering(); // configure filter filterBlob.CoupledSizeFiltering = couple; filterBlob.MinHeight = (int)h.Min; filterBlob.MaxHeight = (int)h.Max; filterBlob.MinWidth = (int)w.Min; filterBlob.MaxWidth = (int)w.Max; // apply the filter newBlobImg = filterBlob.Apply(newBlobImg); //////////////////////////////////////////////////// Bitmap rectImage = (Bitmap)(newBlobImg).Clone(); GrayscaleToRGB convertToColor = new GrayscaleToRGB(); if (rectImage.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed) { rectImage = convertToColor.Apply(newBlobImg); } Graphics g = Graphics.FromImage(rectImage); Pen myPen = new Pen(Color.Red, 1); List <Bitmap> blobIMGs = new List <Bitmap>(); for (int i = 0; i < blobs.Length; i++) { blobIMGs.Add((Bitmap)(newBlobImg).Clone(blobs[i].Rectangle, PixelFormat.Format32bppArgb)); g.DrawRectangle(myPen, blobs[i].Rectangle); } //////////////////////////////////////////////////// Bitmap colorImage = (Bitmap)(newBlobImg).Clone(); ConnectedComponentsLabeling filter = new ConnectedComponentsLabeling(); // apply the filter colorImage = filter.Apply(colorImage); ////////////////////////////////////////////////// SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); Bitmap shapeImage = (Bitmap)(newBlobImg).Clone(); Graphics gg = Graphics.FromImage(shapeImage); Pen yellowPen = new Pen(Color.Yellow, 2); // circles Pen redPen = new Pen(Color.Red, 2); // quadrilateral Pen brownPen = new Pen(Color.Brown, 2); // quadrilateral with known sub-type Pen greenPen = new Pen(Color.Green, 2); // known triangle Pen bluePen = new Pen(Color.Blue, 2); // triangle for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); AForge.Point center; float radius; // is circle ? if (shapeChecker.IsCircle(edgePoints, out center, out radius)) { gg.DrawEllipse(yellowPen, (float)(center.X - radius), (float)(center.Y - radius), (float)(radius * 2), (float)(radius * 2)); } else { List <IntPoint> corners; // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { // get sub-type PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); Pen pen; if (subType == PolygonSubType.Unknown) { pen = (corners.Count == 4) ? redPen : bluePen; } else { pen = (corners.Count == 4) ? brownPen : greenPen; } gg.DrawPolygon(pen, ToPointsArray(corners)); } } } return(new Tuple <Bitmap, Bitmap, Bitmap, Bitmap, List <Bitmap> >(newBlobImg, colorImage, rectImage, shapeImage, blobIMGs)); }
private void ProcessImage(Bitmap bitmap) { // reset counters numberOfCircleShits = 0; numberOfLineShits = 0; numberOfSquareShits = 0; numberOfTriangleShits = 0; // lock image BitmapData bitmapData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); // step 1 - turn background to black ColorFiltering colorFilter = new ColorFiltering(); colorFilter.Red = new IntRange(0, 64); colorFilter.Green = new IntRange(0, 64); colorFilter.Blue = new IntRange(0, 64); colorFilter.FillOutsideRange = false; colorFilter.ApplyInPlace(bitmapData); // step 2 - locating objects BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = 5; blobCounter.MinWidth = 5; blobCounter.ProcessImage(bitmapData); Blob[] blobs = blobCounter.GetObjectsInformation(); bitmap.UnlockBits(bitmapData); // step 3 - check objects' type and highlight SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); Graphics g = Graphics.FromImage(bitmap); for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); AForge.Point center; float radius; // is circle ? if (shapeChecker.IsCircle(edgePoints, out center, out radius)) { numberOfCircleShits++; } else { List <IntPoint> corners; // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { // get sub-type PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); Pen pen; if (subType == PolygonSubType.Square) { numberOfSquareShits++; } else if (subType == PolygonSubType.EquilateralTriangle) { numberOfTriangleShits++; } else { numberOfLineShits++; } } } } g.Dispose(); // put new image to clipboard Clipboard.SetDataObject(bitmap); // and to picture box picture.Image = bitmap; triangleCount.Text = "" + numberOfTriangleShits; CircleCount.Text = "" + numberOfCircleShits; SquareCount.Text = "" + numberOfSquareShits; RectangleCount.Text = "" + +numberOfLineShits; }
public Bitmap Detect(Bitmap bitmap) { Bitmap grayscaleBitmap = Grayscale.CommonAlgorithms.BT709.Apply(bitmap); IFilter smoothingFilter = null; switch (_smoothMode) { case "None": smoothingFilter = null; break; case "Mean": smoothingFilter = new Mean(); break; case "Median": smoothingFilter = new Median(); break; case "Conservative": smoothingFilter = new ConservativeSmoothing(); break; case "Adaptive": smoothingFilter = new AdaptiveSmoothing(); break; case "Bilateral": smoothingFilter = new BilateralSmoothing(); break; } Bitmap smoothBitmap = smoothingFilter != null?smoothingFilter.Apply(grayscaleBitmap) : grayscaleBitmap; IFilter edgeFilter = null; switch (_edgeMode) { case "Homogenity": edgeFilter = new HomogenityEdgeDetector(); break; case "Difference": edgeFilter = new DifferenceEdgeDetector(); break; case "Sobel": edgeFilter = new SobelEdgeDetector(); break; case "Canny": edgeFilter = new CannyEdgeDetector(); break; } Bitmap edgeBitmap = edgeFilter != null?edgeFilter.Apply(smoothBitmap) : smoothBitmap; IFilter threshholdFilter = new Threshold(_threshold); Bitmap thresholdBitmap = _threshold == 0 ? edgeBitmap : threshholdFilter.Apply(edgeBitmap); BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = _minHeight; blobCounter.MinWidth = _minWidth; blobCounter.ProcessImage(thresholdBitmap); Blob[] blobs = blobCounter.GetObjectsInformation(); Bitmap outputBitmap = new Bitmap(thresholdBitmap.Width, thresholdBitmap.Height, PixelFormat.Format24bppRgb); Graphics bitmapGraphics = Graphics.FromImage(outputBitmap); Bitmap inputBitmap = null; switch (_drawMode) { case "Original": inputBitmap = bitmap; break; case "Grayscale": inputBitmap = grayscaleBitmap; break; case "Smooth": inputBitmap = smoothBitmap; break; case "Edge": inputBitmap = edgeBitmap; break; case "Threshold": inputBitmap = thresholdBitmap; break; } if (inputBitmap != null) { bitmapGraphics.DrawImage(inputBitmap, 0, 0); } Pen nonConvexPen = new Pen(Color.Red, 2); Pen nonRectPen = new Pen(Color.Orange, 2); Pen cardPen = new Pen(Color.Blue, 2); SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); List <IntPoint> cardPositions = new List <IntPoint>(); for (int i = 0; i < blobs.Length; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); List <IntPoint> corners; if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); if ((subType == PolygonSubType.Parallelogram || subType == PolygonSubType.Rectangle) && corners.Count == 4) { // Check if its sideways, if so rearrange the corners so it's vertical. RearrangeCorners(corners); // Prevent detecting the same card twice by comparing distance against other detected cards. bool sameCard = false; foreach (IntPoint point in cardPositions) { if (corners[0].DistanceTo(point) < _minDistance) { sameCard = true; break; } } if (sameCard) { continue; } // Hack to prevent it from detecting smaller sections of the card instead of the whole card. if (GetArea(corners) < _minArea) { continue; } cardPositions.Add(corners[0]); bitmapGraphics.DrawPolygon(cardPen, ToPointsArray(corners)); } else { foreach (IntPoint point in edgePoints.Take(300)) { bitmapGraphics.DrawEllipse(nonRectPen, point.X, point.Y, 1, 1); } } } else { foreach (IntPoint point in edgePoints.Take(300)) { bitmapGraphics.DrawEllipse(nonConvexPen, point.X, point.Y, 1, 1); } } } bitmapGraphics.Dispose(); nonConvexPen.Dispose(); nonRectPen.Dispose(); cardPen.Dispose(); return(outputBitmap); }
public void ProcessImage(Bitmap bitmap) { // lock image BitmapData bitmapData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); // step 1 - turn background to black ColorFiltering colorFilter = new ColorFiltering(); // coin.jpg had these boundaries: red <0,64>, green <0,64>, blue <0,64> colorFilter.Red = new IntRange(redBounds[0], redBounds[1]); colorFilter.Green = new IntRange(greenBounds[0], greenBounds[1]); colorFilter.Blue = new IntRange(blueBounds[0], blueBounds[1]); colorFilter.FillOutsideRange = false; colorFilter.ApplyInPlace(bitmapData); // step 2 - locating objects BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = 10; blobCounter.MinWidth = 10; blobCounter.ProcessImage(bitmapData); Blob[] blobs = blobCounter.GetObjectsInformation(); bitmap.UnlockBits(bitmapData); // step 3 - check objects' type and highlight SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); Graphics g = Graphics.FromImage(bitmap); Pen circlePen = new Pen(Color.Yellow, 2); // circles Pen strangeShapePen = new Pen(Color.Red, 2); // quadrilateral with unknown sub-type Pen rectanglePen = new Pen(Color.Brown, 2); // quadrilateral with known sub-type Pen trianglePen = new Pen(Color.Blue, 2); // triangle // step 3.5 - prepare file to save obstacles string path = @"C:\Users\Robert\Documents\Visual Studio 2015\Projects\SMTMotionPlanning\SMTMotionPlanning\obstacleFiles\"; FileStream stream = new FileStream(path + "obstacles.txt", FileMode.Create, FileAccess.Write); StreamWriter writer = new StreamWriter(stream); for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); edgePoints = eliminateDuplicates(edgePoints); AForge.Point center; List <IntPoint> corners; float radius; if (shapeChecker.IsCircle(edgePoints, out center, out radius)) { g.DrawEllipse(circlePen, center.X - radius, center.Y - radius, 2 * radius, 2 * radius); writer.WriteLine("e " + (int)(center.X - radius) + " " + (int)(center.Y - radius) + " " + (int)(radius) + " " + (int)(radius)); } else if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { PolygonSubType polygonType = shapeChecker.CheckPolygonSubType(corners); Pen pen; if (polygonType == PolygonSubType.Rectangle || polygonType == PolygonSubType.Square) { pen = rectanglePen; writer.WriteLine("r " + corners[0].X + " " + corners[0].Y + " " + Math.Abs(corners[0].X - corners[1].X) + " " + Math.Abs(corners[0].Y - corners[2].Y)); g.DrawPolygon(pen, ToPointsArray(corners)); } else { pen = corners.Count == 3 ? trianglePen : strangeShapePen; g.DrawPolygon(pen, ToPointsArray(corners)); writer.Write("p"); foreach (IntPoint corner in corners) { writer.Write(" " + corner.X + " " + corner.Y); } writer.WriteLine(); } } else { corners = orderPolygonCorners(findPolygonCorners(edgePoints), edgePoints); g.DrawPolygon(strangeShapePen, ToPointsArray(corners)); writer.Write("p"); foreach (IntPoint corner in corners) { writer.Write(" " + corner.X + " " + corner.Y); } writer.WriteLine(); } } circlePen.Dispose(); strangeShapePen.Dispose(); trianglePen.Dispose(); rectanglePen.Dispose(); writer.Close(); stream.Close(); g.Dispose(); rescaleCoordinates(); transformCoordinates(); }
private Bitmap FindShapes(Bitmap img, ref Bitmap MarkedImg) { Blob[] Mblobs = new Blob[0]; for (int x = 0; x < 359; x++) { System.Threading.Thread.Sleep(300); // RotateNearestNeighbor filter = new RotateNearestNeighbor(1 , true); // apply the filter // img = filter.Apply(img); RotateBilinear filter = new RotateBilinear(1, true); //apply the filter img = filter.Apply(img); //Find blobs try { BitmapData bitmapData = img.LockBits(new Rectangle(0, 0, img.Width, img.Height), ImageLockMode.ReadWrite, img.PixelFormat); // step 1 - turn background to black ////ColorFiltering colorFilter = new ColorFiltering(); ////colorFilter.Red = new IntRange(0, 64); ////colorFilter.Green = new IntRange(0, 64); ////colorFilter.Blue = new IntRange(0, 64); ////colorFilter.FillOutsideRange = false; ////colorFilter.ApplyInPlace(bitmapData); // step 2 - locating objects BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = 15; blobCounter.MinWidth = 15; blobCounter.MaxHeight = 100; blobCounter.MaxWidth = 100; blobCounter.ProcessImage(bitmapData); Blob[] blobs = blobCounter.GetObjectsInformation(); img.UnlockBits(bitmapData); if (Mblobs.Length == 0 && blobs.Length > 0) { Mblobs = new Blob[blobs.Length]; blobs.CopyTo(Mblobs, 0); } else if (Mblobs.Length > 0 && blobs.Length > 0) { Blob[] temp = Mblobs; Mblobs = new Blob[temp.Length + blobs.Length]; temp.CopyTo(Mblobs, 0); blobs.CopyTo(Mblobs, Mblobs.Length - 1); } //find shapes SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); Graphics g = Graphics.FromImage(MarkedImg); Pen yellowPen = new Pen(Color.Yellow, 4); // circles Pen redPen = new Pen(Color.Red, 4); // quadrilateral Pen brownPen = new Pen(Color.Brown, 4); // quadrilateral with known sub-type Pen greenPen = new Pen(Color.Green, 4); // known triangle Pen bluePen = new Pen(Color.Blue, 4); // triangle //test draw // g.DrawEllipse(redPen, MarkedImg.Width / 2 + 10, MarkedImg.Height / 2,1, 20); // g.DrawEllipse(redPen, MarkedImg.Width / 2, MarkedImg.Height / 2+10, 20, 1); for (int i = 0; i < Mblobs.Length; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(Mblobs[i]); AForge.Point center; float radius; // is circle ? if (shapeChecker.IsCircle(edgePoints, out center, out radius)) { g.DrawEllipse(yellowPen, (float)(center.X - radius), (float)(center.Y - radius), (float)(radius * 2), (float)(radius * 2)); } else { List <IntPoint> corners; // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { // get sub-type PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); Pen pen; if (subType == PolygonSubType.Unknown) { pen = (corners.Count == 4) ? redPen : bluePen; } else { pen = (corners.Count == 4) ? brownPen : greenPen; } g.DrawPolygon(pen, ToPointsArray(corners)); } } } yellowPen.Dispose(); redPen.Dispose(); greenPen.Dispose(); bluePen.Dispose(); brownPen.Dispose(); g.Dispose(); pbCapture.Image = img; //set picturebox image---------------- pbShapes.Image = MarkedImg; //set picturebox image---------------- } catch (Exception ex) { MessageBox.Show(ex.Message); } } ///////////////////////////////////////////// ///////////////////////////////////////////////////////// return(img); }
private void ProcessImage(Bitmap bitmap) { // lock image BitmapData bitmapData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); // step 1 - turn background to black ColorFiltering colorFilter = new ColorFiltering(); colorFilter.Red = new IntRange(Properties.Settings.Default.camFilterRed1, Properties.Settings.Default.camFilterRed2); colorFilter.Green = new IntRange(Properties.Settings.Default.camFilterGreen1, Properties.Settings.Default.camFilterGreen2); colorFilter.Blue = new IntRange(Properties.Settings.Default.camFilterBlue1, Properties.Settings.Default.camFilterBlue2); colorFilter.FillOutsideRange = Properties.Settings.Default.camFilterOutside; colorFilter.ApplyInPlace(bitmapData); // step 2 - locating objects BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = (int)Properties.Settings.Default.camShapeSizeMin * (int)cameraZoom; blobCounter.MinWidth = (int)Properties.Settings.Default.camShapeSizeMin * (int)cameraZoom; blobCounter.MaxHeight = (int)Properties.Settings.Default.camShapeSizeMax * (int)cameraZoom; blobCounter.MaxWidth = (int)Properties.Settings.Default.camShapeSizeMax * (int)cameraZoom; blobCounter.ProcessImage(bitmapData); Blob[] blobs = blobCounter.GetObjectsInformation(); bitmap.UnlockBits(bitmapData); // step 3 - check objects' type and highlight SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); shapeChecker.MinAcceptableDistortion = (float)Properties.Settings.Default.camShapeDist; shapeChecker.RelativeDistortionLimit = (float)Properties.Settings.Default.camShapeDistMax; Graphics g = Graphics.FromImage(bitmap); Pen yellowPen = new Pen(Color.Yellow, 5); // circles Pen redPen = new Pen(Color.Red, 10); // circles Pen greenPen = new Pen(Color.Green, 5); // known triangle double lowestDistance = xmid; double distance; shapeFound = false; AForge.Point center; double shapeRadius = 1; for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); System.Single radius; // is circle ? // g.DrawPolygon(greenPen, ToPointsArray(edgePoints)); if (Properties.Settings.Default.camShapeCircle && shapeChecker.IsCircle(edgePoints, out center, out radius)) { shapeFound = true; distance = center.DistanceTo((AForge.Point)picCenter); g.DrawEllipse(yellowPen, (float)(shapeCenter.X - shapeRadius), (float)(shapeCenter.Y - shapeRadius), (float)(shapeRadius * 2), (float)(shapeRadius * 2)); if (lowestDistance > Math.Abs(distance)) { lowestDistance = Math.Abs(distance); shapeCenter = center; shapeRadius = radius; } } List <IntPoint> corners; if (Properties.Settings.Default.camShapeRect && shapeChecker.IsQuadrilateral(edgePoints, out corners)) //.IsConvexPolygon { IntPoint minxy, maxxy, centxy; shapeFound = true; PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); g.DrawPolygon(yellowPen, ToPointsArray(corners)); PointsCloud.GetBoundingRectangle(corners, out minxy, out maxxy); centxy = (minxy + maxxy) / 2; distance = picCenter.DistanceTo(centxy);// PointsCloud.GetCenterOfGravity(corners)); if (lowestDistance > Math.Abs(distance)) { lowestDistance = Math.Abs(distance); shapeCenter = centxy; // PointsCloud.GetCenterOfGravity(corners); shapeRadius = maxxy.DistanceTo(minxy) / 2; // 50; } } } if (shapeFound) { g.DrawEllipse(redPen, (float)(shapeCenter.X - shapeRadius * 1.2), (float)(shapeCenter.Y - shapeRadius * 1.2), (float)(shapeRadius * 2.4), (float)(shapeRadius * 2.4)); } yellowPen.Dispose(); redPen.Dispose(); greenPen.Dispose(); g.Dispose(); pictureBoxVideo.BackgroundImage = bitmap; }
public Bitmap ProcesarImagen(Bitmap mapaBits) { numeroCirculos = 0; numeroRectanculos = 0; numeroCuadrados = 0; numeroTriangulos = 0; // bloquear imágen BitmapData datosMapaBits = mapaBits.LockBits( new Rectangle(0, 0, mapaBits.Width, mapaBits.Height), ImageLockMode.ReadWrite, mapaBits.PixelFormat); // Paso 1 - Fondo a negro ColorFiltering filtroColor = new ColorFiltering(); filtroColor.Red = new IntRange(0, 64); filtroColor.Green = new IntRange(0, 64); filtroColor.Blue = new IntRange(0, 64); filtroColor.FillOutsideRange = false; filtroColor.ApplyInPlace(datosMapaBits); // paso 2 - Localizar objetos BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = 5; blobCounter.MinWidth = 5; blobCounter.ProcessImage(datosMapaBits); Blob[] blobs = blobCounter.GetObjectsInformation(); mapaBits.UnlockBits(datosMapaBits); // step 3 - check objects' type and highlight SimpleShapeChecker verificadorFormas = new SimpleShapeChecker(); Graphics g = Graphics.FromImage(mapaBits); Pen plumaAmarilla = new Pen(Color.Yellow, 5); // Circulo Pen plumaRoja = new Pen(Color.Red, 5); // Cuadrilatero Pen plumaCafe = new Pen(Color.Brown, 5); // Cuadrilatero Pen plumaVerde = new Pen(Color.Green, 5); // Triangulo Pen plumaAzul = new Pen(Color.Blue, 5); // Triangulo for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> bordes = blobCounter.GetBlobsEdgePoints(blobs[i]); DoublePoint centro; double radio; // Verificar si es círculo if (verificadorFormas.IsCircle(bordes, out centro, out radio)) { g.DrawEllipse(plumaAmarilla, (float)(centro.X - radio), (float)(centro.Y - radio), (float)(radio * 2), (float)(radio * 2)); numeroCirculos++; PantallaEstacion.cantidadFiguras[0] = numeroCirculos; } else { List <IntPoint> esquinas; // Verificar si es triángulo o cuadrilátero if (verificadorFormas.IsConvexPolygon(bordes, out esquinas)) { // obtener subtipo PolygonSubType subTipo = verificadorFormas.CheckPolygonSubType(esquinas); Pen pluma; if (subTipo == PolygonSubType.Unknown) { pluma = (esquinas.Count == 4) ? plumaRoja : plumaAzul; //Rectangulo numeroRectanculos++; PantallaEstacion.cantidadFiguras[2] = numeroRectanculos; } else { if (esquinas.Count == 4) { pluma = plumaCafe; numeroCuadrados++; PantallaEstacion.cantidadFiguras[1] = numeroCuadrados; } else { pluma = plumaVerde; numeroTriangulos++; PantallaEstacion.cantidadFiguras[3] = numeroTriangulos; } } g.DrawPolygon(pluma, ToPointsArray(esquinas)); } } } plumaAmarilla.Dispose(); plumaRoja.Dispose(); plumaVerde.Dispose(); plumaAzul.Dispose(); plumaCafe.Dispose(); g.Dispose(); numeroCuadrados--; //Por el rectángulo del borde de la imágen. Console.WriteLine("Rectangulos:{0}\nCirculos:{1}\nTriangulos:{2}\nCuadrados{3}", numeroRectanculos, numeroCirculos, numeroTriangulos, numeroCuadrados); return(mapaBits); }
private System.Drawing.Rectangle?FindHealthbarRect() { var healthArea = CaptureApexWindow(); // locating objects var blobCounter = new BlobCounter(); blobCounter.CoupledSizeFiltering = true; blobCounter.FilterBlobs = true; blobCounter.MinHeight = 6; blobCounter.MinWidth = 100; blobCounter.MaxHeight = 15; //grayscale var bmp = Grayscale.CommonAlgorithms.BT709.Apply(healthArea); //Invert invert = new Invert(); //bmp = invert.Apply(bmp); var filter = new IterativeThreshold(2, 4); // apply the filter filter.ApplyInPlace(bmp); blobCounter.ProcessImage(bmp); Blob[] blobs = blobCounter.GetObjectsInformation(); // check for rectangles var shapeChecker = new SimpleShapeChecker(); shapeChecker.AngleError = 5.0f; shapeChecker.LengthError = 0.5f; foreach (var blob in blobs) { List <AForge.IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blob); List <AForge.IntPoint> cornerPoints; try { // use the shape checker to extract the corner points if (shapeChecker.IsQuadrilateral(edgePoints, out cornerPoints)) { PolygonSubType subType = shapeChecker.CheckPolygonSubType(cornerPoints); if (subType == PolygonSubType.Trapezoid) { // here i use the graphics class to draw an overlay, but you // could also just use the cornerPoints list to calculate your // x, y, width, height values. List <System.Drawing.Point> Points = new List <System.Drawing.Point>(); foreach (var point in cornerPoints) { Points.Add(new System.Drawing.Point(point.X, point.Y)); } var boundingBox = GetBoundingBox(Points); var ratio = (boundingBox.Width / (float)boundingBox.Height); if (ratio > 21.0f && ratio < 24.0f) { return(boundingBox); } } } } catch (Exception e) { } } return(null); }
private void kamerica_NewFrame(object sender, NewFrameEventArgs eventArgs) { Bitmap slika = (Bitmap)eventArgs.Frame.Clone(); BitmapData bitmapData = slika.LockBits( new Rectangle(0, 0, slika.Width, slika.Height), ImageLockMode.ReadWrite, slika.PixelFormat); // step 1 - turn background to black ColorFiltering colorFilter = new ColorFiltering(); colorFilter.Red = new IntRange(0, 64); colorFilter.Green = new IntRange(0, 64); colorFilter.Blue = new IntRange(0, 64); colorFilter.FillOutsideRange = false; colorFilter.ApplyInPlace(bitmapData); // step 2 - locating objects BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = 5; blobCounter.MinWidth = 5; blobCounter.ProcessImage(bitmapData); Blob[] blobs = blobCounter.GetObjectsInformation(); slika.UnlockBits(bitmapData); // step 3 - check objects' type and highlight SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); Graphics g = Graphics.FromImage(slika); Pen yellowPen = new Pen(Color.Yellow, 2); // circles Pen redPen = new Pen(Color.Red, 2); // quadrilateral Pen brownPen = new Pen(Color.Brown, 2); // quadrilateral with known sub-type Pen greenPen = new Pen(Color.Green, 2); // known triangle Pen bluePen = new Pen(Color.Blue, 2); // triangle for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); // calculate center point AForge.Point center; // calculate radius float radius; // is circle ? if (shapeChecker.IsCircle(edgePoints, out center, out radius)) { g.DrawEllipse(yellowPen, (float)(center.X - radius), (float)(center.Y - radius), (float)(radius * 2), (float)(radius * 2)); } else { List <IntPoint> corners; // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { // get sub-type PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); Pen pen; if (subType == PolygonSubType.Unknown) { pen = (corners.Count == 4) ? redPen : bluePen; } else { pen = (corners.Count == 4) ? brownPen : greenPen; } g.DrawPolygon(pen, ToPointsArray(corners)); } } } yellowPen.Dispose(); redPen.Dispose(); greenPen.Dispose(); bluePen.Dispose(); brownPen.Dispose(); g.Dispose(); pictureBox1.Image = slika; }
public void nesnebul(Bitmap image) { BlobCounter blobCounter = new BlobCounter(); blobCounter.MinWidth = 5; blobCounter.MinHeight = 5; blobCounter.FilterBlobs = true; blobCounter.ObjectsOrder = ObjectsOrder.Size; //Grayscale griFiltre = new Grayscale(0.2125, 0.7154, 0.0721); //Grayscale griFiltre = new Grayscale(0.2, 0.2, 0.2); //Bitmap griImage = griFiltre.Apply(image); BitmapData objectsData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, image.PixelFormat); // grayscaling Grayscale grayscaleFilter = new Grayscale(0.2125, 0.7154, 0.0721); UnmanagedImage grayImage = grayscaleFilter.Apply(new UnmanagedImage(objectsData)); // unlock image image.UnlockBits(objectsData); blobCounter.ProcessImage(image); Rectangle[] rects = blobCounter.GetObjectsRectangles(); Blob[] blobs = blobCounter.GetObjectsInformation(); pictureBox2.Image = image; if (radio_single_object_track.Checked) { //Single Object Tracking Single Tracking-------- foreach (Rectangle recs in rects) { if (rects.Length > 0) { Rectangle objectRect = rects[0]; //Graphics g = Graphics.FromImage(image); Graphics g = pictureBox1.CreateGraphics(); Graphics g2 = pictureBox2.CreateGraphics(); using (Pen pen = new Pen(Color.FromArgb(252, 3, 26), 2)) { g.DrawRectangle(pen, objectRect); } //Coordinates of the rectified rectangle are taken. int objectX = objectRect.X + (objectRect.Width / 2); int objectY = objectRect.Y + (objectRect.Height / 2); g.DrawString(objectX.ToString() + "X" + objectY.ToString(), new Font("Arial", 12), Brushes.Red, new System.Drawing.Point(250, 1)); Rectangle rec = new Rectangle(objectX, objectY, 5, 5); g2.DrawEllipse(Pens.White, rec); g.Dispose(); if (chek_show_coordi.Checked) { this.Invoke((MethodInvoker) delegate { richTextBox1.Text = objectRect.Location.ToString() + "\n" + richTextBox1.Text + "\n";; }); } } } } if (radio_multi_obj_track.Checked) { //Multi tracking Çoklu cisim Takibi------- for (int i = 0; rects.Length > i; i++) { Rectangle objectRect = rects[i]; //Graphics g = Graphics.FromImage(image); Graphics g = pictureBox1.CreateGraphics(); using (Pen pen = new Pen(Color.FromArgb(252, 3, 26), 2)) { g.DrawRectangle(pen, objectRect); g.DrawString((i + 1).ToString(), new Font("Arial", 12), Brushes.Red, objectRect); } //Cizdirilen Dikdörtgenin Koordinatlari aliniyor. int objectX = objectRect.X + (objectRect.Width / 2); int objectY = objectRect.Y + (objectRect.Height / 2); g.DrawString(objectX.ToString() + "X" + objectY.ToString(), new Font("Arial", 12), Brushes.Red, new System.Drawing.Point(250, 1)); if (chck_dis_meter.Checked) { if (rects.Length > 1) { for (int j = 0; j < rects.Length - 1; j++) { int ilkx = (rects[j].Right + rects[j].Left) / 2; int ilky = (rects[j].Top + rects[j].Bottom) / 2; int ikix = (rects[j + 1].Right + rects[j + 1].Left) / 2; int ikiy = (rects[j + 1].Top + rects[j + 1].Bottom) / 2; g = pictureBox1.CreateGraphics(); g.DrawLine(Pens.Red, rects[j].Location, rects[j + 1].Location); g.DrawLine(Pens.Blue, rects[0].Location, rects[rects.Length - 1].Location); g.DrawLine(Pens.Red, ilkx, ilky, ikix, ikiy); } } if (rects.Length == 2) { Rectangle ilk = rects[0]; Rectangle iki = rects[1]; int ilkX = ilk.X + (ilk.Width / 2); int ilkY = ilk.Y + (ilk.Height / 2); int ikiX = iki.X + (iki.Width / 2); int ikiY = iki.Y + (iki.Height / 2); //1 pixel (X) = 0.0264583333333334 centimeter [cm] double formul = Math.Floor((Math.Sqrt((Math.Pow((ilkX - ikiX), 2)) + Math.Pow((ilkY - ikiY), 2))) * 0.0264); string uzaklikY = "Y-" + Convert.ToString(ilkX - ikiX); string uzaklikX = "X-" + Convert.ToString(ilkY - ikiY); string distance = uzaklikX + " " + uzaklikY; AForge.Imaging.Drawing.Line(objectsData, new IntPoint((int)ilkX, (int)ilkY), new IntPoint((int)ikiX, (int)ikiY), Color.Blue); this.Invoke((MethodInvoker) delegate { richTextBox2.Text = formul.ToString() + " cm\n" + richTextBox2.Text + " cm\n";; }); if (check_dist_coord.Checked) { this.Invoke((MethodInvoker) delegate { richTextBox3.Text = distance.ToString() + "\n" + richTextBox3.Text + "\n";; }); } } } g.Dispose(); // this.Invoke((MethodInvoker)delegate //{ // richTextBox1.Text = objectRect.Location.ToString() + "\n" + richTextBox1.Text + "\n"; ; //}); } } if (radio_geometric.Checked) { SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); Graphics g = pictureBox1.CreateGraphics(); Pen yellowPen = new Pen(Color.Yellow, 2); // circles Pen redPen = new Pen(Color.Red, 2); // quadrilateral Pen brownPen = new Pen(Color.Brown, 2); // quadrilateral with known sub-type Pen greenPen = new Pen(Color.Green, 2); // known triangle Pen bluePen = new Pen(Color.Blue, 2); // triangle for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); AForge.Point center; float radius; // is circle ? if (shapeChecker.IsCircle(edgePoints, out center, out radius)) { g.DrawEllipse(yellowPen, (float)(center.X - radius), (float)(center.Y - radius), (float)(radius * 2), (float)(radius * 2)); } else { List <IntPoint> corners; // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { // get sub-type PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); Pen pen; if (subType == PolygonSubType.Unknown) { pen = (corners.Count == 4) ? redPen : bluePen; } else { pen = (corners.Count == 4) ? brownPen : greenPen; } g.DrawPolygon(pen, ToPointsArray(corners)); } } } yellowPen.Dispose(); redPen.Dispose(); greenPen.Dispose(); bluePen.Dispose(); brownPen.Dispose(); g.Dispose(); } }
public VisionLocationResult LocateObjects() { VisionLocationResult ld = new VisionLocationResult(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "", 0, 0, null); int totalwidth = 0; int totalheight = 0; System.Drawing.Point centerpoint = new System.Drawing.Point(); if (currentImage != null) { try { Bitmap image = new Bitmap(this.currentImage); totalwidth = image.Width; totalheight = image.Height; centerpoint.X = image.Width / 2; centerpoint.Y = image.Height / 2; // lock image BitmapData bmData = image.LockBits( new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, image.PixelFormat); // turn background to black ColorFiltering cFilter = new ColorFiltering(red: new IntRange(0, 64), green: new IntRange(0, 64), blue: new IntRange(0, 64)); //cFilter.Red = new IntRange(0, 64); //cFilter.Green = new IntRange(0, 64); //cFilter.Blue = new IntRange(0, 64); cFilter.FillOutsideRange = false; cFilter.ApplyInPlace(bmData); // locate objects BlobCounter bCounter = new BlobCounter(); bCounter.FilterBlobs = true; bCounter.MinHeight = 10; bCounter.MinWidth = 10; bCounter.ProcessImage(bmData); Blob[] baBlobs = bCounter.GetObjectsInformation(); image.UnlockBits(bmData); // coloring objects SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); Graphics g = Graphics.FromImage(image); Pen bluePen = new Pen(Color.Blue, 2); Pen whitepen = new Pen(Color.White, 1); for (int i = 0, n = baBlobs.Length; i < n; i++) { List <IntPoint> edgePoints = bCounter.GetBlobsEdgePoints(baBlobs[i]); Rectangle[] _rects = bCounter.GetObjectsRectangles(); List <IntPoint> corners; // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); Pen pen; if (subType == PolygonSubType.Rectangle && corners.Count == 4) { pen = bluePen; ld.Loc1X = corners[0].X; ld.Loc1Y = corners[0].Y; ld.Loc2X = corners[1].X; ld.Loc2Y = corners[1].Y; ld.Loc3X = corners[2].X; ld.Loc3Y = corners[2].Y; ld.Loc4X = corners[3].X; ld.Loc4Y = corners[3].Y; // find longest side of rectangle double side1 = corners[0].DistanceTo(corners[1]); double side2 = corners[1].DistanceTo(corners[2]); double angleInRadians = 0; double deltaY = 0; double deltaX = 0; int select1 = 0; int select2 = 1; if (side1 < side2) { select1 = 1; select2 = 2; ld.ItemWidth = side2; ld.ItemHeight = side1; } else { ld.ItemWidth = side1; ld.ItemHeight = side2; } // find angle of longest side angleInRadians = Math.Atan2(corners[select1].Y, corners[select1].X) - Math.Atan2(corners[select2].Y, corners[select2].X); deltaY = Math.Abs(corners[select2].Y - corners[select1].Y); deltaX = Math.Abs(corners[select2].X - corners[select1].X); double angleInDegrees = Math.Atan2(deltaY, deltaX) * 180 / Math.PI; ld.LocAngle = angleInDegrees; ld.OffsetY = PixelsToMM((GetCenter(corners).X - (totalwidth / 2)) * -1); ld.OffsetX = PixelsToMM(GetCenter(corners).Y - (totalheight / 2)); ld.LocText = "side1: " + side1.ToString() + Environment.NewLine + "side2: " + side2.ToString() + Environment.NewLine + "Center X: " + GetCenter(corners).X + "Center Y: " + GetCenter(corners).Y + Environment.NewLine + "Image Center: " + (totalwidth / 2).ToString() + " x " + (totalheight / 2).ToString(); System.Drawing.Point[] _coordinates = ToPointsArray(corners); // draw outline and corners g.DrawPolygon(pen, _coordinates); // draw center cross lines on image g.DrawLine(whitepen, new System.Drawing.Point(0, totalheight / 2), new System.Drawing.Point(totalwidth, totalheight / 2)); g.DrawLine(whitepen, new System.Drawing.Point(totalwidth / 2, 0), new System.Drawing.Point(totalwidth / 2, totalheight)); ld.Image = image; } } } whitepen.Dispose(); bluePen.Dispose(); g.Dispose(); this.currentImage = image; return(ld); } catch (Exception e) { MessageBox.Show(e.ToString()); } } return(ld); }
private void ProcessImage(Bitmap bitmap) { // lock image BitmapData bitmapData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); // step 1 - turn background to black ColorFiltering colorFilter = new ColorFiltering(); colorFilter.Red = new IntRange(0, 64); colorFilter.Green = new IntRange(0, 64); colorFilter.Blue = new IntRange(0, 64); colorFilter.FillOutsideRange = false; colorFilter.ApplyInPlace(bitmapData); // step 2 - locating objects BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = 5; blobCounter.MinWidth = 5; blobCounter.ProcessImage(bitmapData); Blob[] blobs = blobCounter.GetObjectsInformation(); bitmap.UnlockBits(bitmapData); SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); Graphics g = Graphics.FromImage(bitmap); Pen brownPen = new Pen(Color.Red, 3); for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); List <IntPoint> corners; if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); if (subType == PolygonSubType.Unknown) { if (corners.Count == 4) { g.DrawPolygon(brownPen, ToPointsArray(corners)); } } else { if (corners.Count == 4) { g.DrawPolygon(brownPen, ToPointsArray(corners)); } } } } brownPen.Dispose(); g.Dispose(); Clipboard.SetDataObject(bitmap); pictureBox5.Image = bitmap; }
static void Main(string[] args) { try { bool parm_error = false; if (args.Length == 0) { exitWithHelp(); // Exit! No param } //set mandatory parm string in_path = ""; //optional parm bool cropcenter = false; bool emulate = false; bool debug = false; //optional blob parm bool blob = false; string bfilterw = ""; double bfilterw_min = 1; double bfilterw_max = 1; string bfilterh = ""; double bfilterh_min = 1; double bfilterh_max = 1; bool blob_noff = false; bool blob_noshape = false; bool blob_notrotate = false; string blob_zone = ""; double blob_zonex = 0.5; double blob_zoney = 0.5; //parsing parm for (int p = 0; p < args.Length; p++) { //for each parm get type and value //ex. -parm value -parm2 value2 //get parm switch (args[p]) { case "-debug": debug = true; break; case "-f": in_path = args[p + 1]; break; case "-cropcenter": cropcenter = true; break; case "-emulate": emulate = true; break; case "-blob": blob = true; break; case "-bfilterw": bfilterw = args[p + 1]; break; case "-bfilterh": bfilterh = args[p + 1]; break; case "-bnoff": blob_noff = true; break; case "-bzone": blob_zone = args[p + 1]; break; case "-bnoshape": blob_noshape = true; break; case "-bnotrotate": blob_notrotate = true; break; default: if (args[p].StartsWith("-")) { exitNotValid(args[p]); // Exit! Invalid param } break; } } //check mandatory param if (in_path.Equals("")) { exitWithHelp(); } //check others param if (!bfilterw.Equals("")) { RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline; Regex pattern = new Regex(@"((?:[0]\.)?\d+)\-((?:[0]\.)?\d+)", options); Match match = pattern.Match(bfilterw); if (match.Success && match.Groups.Count.Equals(3)) { bfilterw_min = Convert.ToDouble(match.Groups[1].Value.Replace('.', ',')); bfilterw_max = Convert.ToDouble(match.Groups[2].Value.Replace('.', ',')); } else { exitWithError("Opzione '-bfilterw' non valida.", "Specificare i valori minimi e massimi nel seguente formato:", " -bfilterw valoremin-valoremax", " es. -bfilterw 0.30-0.40"); } } if (!bfilterh.Equals("")) { RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline; Regex pattern = new Regex(@"((?:[0]\.)?\d+)\-((?:[0]\.)?\d+)", options); Match match = pattern.Match(bfilterh); if (match.Success && match.Groups.Count.Equals(3)) { bfilterh_min = Convert.ToDouble(match.Groups[1].Value.Replace('.', ',')); bfilterh_max = Convert.ToDouble(match.Groups[2].Value.Replace('.', ',')); } else { exitWithError("Opzione '-bfilterh' non valida.", "Specificare i valori minimi e massimi nel seguente formato:", " -bfilterh valoremin-valoremax", " es. -bfilterh 0.30-0.40"); } } if (!blob_zone.Equals("")) { RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline; Regex pattern = new Regex(@"((?:[0]\.)?\d+)\,((?:[0]\.)?\d+)", options); Match match = pattern.Match(blob_zone); if (match.Success && match.Groups.Count.Equals(3)) { blob_zonex = Convert.ToDouble(match.Groups[1].Value.Replace('.', ',')); blob_zoney = Convert.ToDouble(match.Groups[2].Value.Replace('.', ',')); } else { exitWithError("Opzione '-bzone' non valida.", "Specificare le coordinate del punto dove cercare il barcode.", " -bzone x,y", " es. -bzone 0.5,0.5"); } } //check validity if (File.Exists(in_path)) { in_path = Path.GetFullPath(in_path); } else { exitFileNotFound(in_path); } //START Stopwatch stopWatch = new Stopwatch(); if (emulate) { stopWatch.Start(); } //Convert to image if PDF string tmp_path = ""; bool tmp_file = false; if (Path.GetExtension(in_path).Equals(".pdf")) { if (debug) { Console.WriteLine("Converting pdf..."); } tmp_path = in_path + ".png"; tmp_file = true; libImage.ConvertSingleImage(in_path, tmp_path, 300); } else { tmp_path = in_path; } //Load image in memory and del file System.Drawing.Bitmap tmp_img; using (System.Drawing.Bitmap img_source = (Bitmap)Bitmap.FromFile(tmp_path)) { tmp_img = new Bitmap(img_source); } if (tmp_file) { File.Delete(tmp_path); } //Get Info on page int page_w = tmp_img.Width; int page_h = tmp_img.Height; if (debug) { Console.WriteLine("File dimension: w=" + page_w + " h=" + page_h); } //Crop Center if (cropcenter) { if (debug) { Console.WriteLine("Cropping central image..."); } int crop_x = Convert.ToInt32(((double)tmp_img.Width * 0.3)), crop_y = Convert.ToInt32(((double)tmp_img.Height * 0.3)), crop_width = Convert.ToInt32(((double)tmp_img.Width * 0.7) - crop_x), crop_height = Convert.ToInt32(((double)tmp_img.Height * 0.7) - crop_y); //source = source.crop(crop_x, crop_y, crop_width, crop_height); tmp_img = tmp_img.Clone(new Rectangle(crop_x, crop_y, crop_width, crop_height), PixelFormat.Format32bppArgb); page_w = tmp_img.Width; page_h = tmp_img.Height; if (debug) { Console.WriteLine("New file dimension: w=" + page_w + " h=" + page_h); } } else { tmp_img = AForge.Imaging.Image.Clone(tmp_img, PixelFormat.Format32bppArgb); } //Blob Analysis if (blob) { if (debug) { Console.WriteLine("Starting Blob Analysis..."); } // filter GreyScale Grayscale filterg = new Grayscale(0.2125, 0.7154, 0.0721); tmp_img = filterg.Apply(tmp_img); Bitmap tmp_img_wrk = (Bitmap)tmp_img.Clone(); // filter Erosion3x3 BinaryErosion3x3 filter = new BinaryErosion3x3(); tmp_img_wrk = filter.Apply(tmp_img_wrk); tmp_img_wrk = filter.Apply(tmp_img_wrk); tmp_img_wrk = filter.Apply(tmp_img_wrk); tmp_img_wrk = filter.Apply(tmp_img_wrk); tmp_img_wrk = filter.Apply(tmp_img_wrk); tmp_img_wrk = filter.Apply(tmp_img_wrk); //Binarization SISThreshold filterSIS = new SISThreshold(); tmp_img_wrk = filterSIS.Apply(tmp_img_wrk); //Inversion Invert filterI = new Invert(); tmp_img_wrk = filterI.Apply(tmp_img_wrk); //Blob Analisys BlobCounterBase bc = new BlobCounter(); bc.FilterBlobs = true; if (!bfilterw.Equals("")) { bc.MinWidth = Convert.ToInt32(page_w * bfilterw_min); // 0.15 in proporzione è il 20% bc.MaxWidth = Convert.ToInt32(page_w * bfilterw_max); // 0.30 } if (!bfilterh.Equals("")) { bc.MinHeight = Convert.ToInt32(page_h * bfilterh_min); // 0.10 in proporzione è il 15% bc.MaxHeight = Convert.ToInt32(page_h * bfilterh_max); // 0.20 } if (debug) { Console.WriteLine("Searching blob (Dimension filter: w=" + bc.MinWidth + "-" + (bc.MaxWidth.Equals(int.MaxValue) ? "max" : bc.MaxWidth.ToString()) + " h=" + bc.MinHeight + "-" + (bc.MaxHeight.Equals(int.MaxValue) ? "max": bc.MaxHeight.ToString()) + ")"); } bc.ObjectsOrder = ObjectsOrder.Size; bc.ProcessImage(tmp_img_wrk); Blob[] blobs = bc.GetObjectsInformation(); if (debug) { Console.WriteLine("Blobs found: " + blobs.Count()); } //Esamina Blobs int i = 1; foreach (Blob b in blobs) { //Escludi blob contenitore (l'immagine stessa) if (b.Rectangle.Width == page_w) { if (debug) { Console.WriteLine("Blob " + i + ": skip! (is container)"); } i++; continue; } //check form factor if (!blob_noff) { double formf = (Convert.ToDouble(b.Rectangle.Width) / Convert.ToDouble(b.Rectangle.Height)) * 100; if (formf < 95) { //skip Form Factor Not a square if (debug) { Console.WriteLine("Blob " + i + ": Check 1 - Form factor > 95 Failed! (form factor is not square " + formf + "<95) Blob Skipped!"); Console.WriteLine("You can disable this check with -bnoff parameter."); } i++; continue; } if (debug) { Console.WriteLine("Blob " + i + ": Check 1 - Form factor > 95 " + formf + " Ok!"); } } else if (debug) { Console.WriteLine("Blob " + i + ": Check 1 - Form factor > 95 skipped by option -bnoff "); } //check zone if (!blob_zone.Equals("")) { Rectangle bZone = b.Rectangle; bZone.Inflate(Convert.ToInt32(b.Rectangle.Width * 0.2), Convert.ToInt32(b.Rectangle.Height * 0.2)); if (!bZone.Contains(Convert.ToInt32(page_w * blob_zonex), Convert.ToInt32(page_h * blob_zoney))) { //skip Zone Not in center if (debug) { Console.WriteLine("Blob " + i + ": Check 2 - Zone of blob Failed! (Not in the zone requested! blob zone:" + b.Rectangle.ToString() + " and requested point is at x=" + Convert.ToInt32(page_w * blob_zonex) + ",y=" + Convert.ToInt32(page_h * blob_zonex) + " ) Blob Skipped!"); } i++; continue; } if (debug) { Console.WriteLine("Blob " + i + ": Check 2 - Zone of blob contains " + Convert.ToInt32(page_w * blob_zonex) + "," + Convert.ToInt32(page_h * blob_zonex) + "... Ok!"); } } //check shape List <IntPoint> edgePoints = bc.GetBlobsEdgePoints(b); List <IntPoint> corners; SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); if (shapeChecker.IsQuadrilateral(edgePoints, out corners)) { if (!blob_noshape) { PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); if (!subType.Equals(PolygonSubType.Square)) { //skip Not a square if (debug) { Console.WriteLine("Blob " + i + ": Check 3 - Shape is Square Failed! (Shape is not Square! " + subType.ToString() + " detected!) Blob Skipped!"); Console.WriteLine("You can disable this check with -bnoshape parameter."); } i++; continue; } else if (debug) { Console.WriteLine("Blob " + i + ": Check 3 - Shape is Square Ok!"); } } else if (debug) { Console.WriteLine("Blob " + i + ": Check 3 - Shape is Square skipped by option -bnoshape "); } } else { shapeChecker.ToString(); //skip Not a quadrilateral if (debug) { Console.WriteLine("Blob " + i + ": Check 3 - Shape is Square... Failed! (not a Quadrilateral! ConvexPolygon:" + shapeChecker.IsConvexPolygon(edgePoints, out corners) + " Triangle:" + shapeChecker.IsTriangle(edgePoints, out corners) + ") Blob Skipped!"); } i++; continue; } //if (debug){ Console.WriteLine("Blob " + i + ": Trying to decode..."); } //Calculate rotation angle 0 bottom left , 1 top left , 2 top right, 3 bottom right double dx = corners[2].X - corners[1].X; double dy = corners[1].Y - corners[2].Y; double ang = Math.Atan2(dx, dy) * (180 / Math.PI); if (ang > 90) { ang = ang - 90; } else { ang = 90 - ang; } //Extract Blob Rectangle cropRect = b.Rectangle; cropRect.Inflate(Convert.ToInt32(b.Rectangle.Width * 0.1), Convert.ToInt32(b.Rectangle.Height * 0.1)); Crop filter_blob = new Crop(cropRect); Bitmap tmp_img_blob = filter_blob.Apply(tmp_img); //Rotate if (!blob_notrotate) { RotateBilinear filterRotate = new RotateBilinear(ang, true); tmp_img_blob = filterRotate.Apply(tmp_img_blob); //Togli margine esterno (bande nere derivanti dalla rotazione) Rectangle cropRectInterno = new Rectangle(0, 0, tmp_img_blob.Width, tmp_img_blob.Height); cropRectInterno.Inflate(-Convert.ToInt32(b.Rectangle.Width * 0.05), -Convert.ToInt32(b.Rectangle.Height * 0.05)); Crop filterCropInterno = new Crop(cropRectInterno); tmp_img_blob = filterCropInterno.Apply(tmp_img_blob); if (debug) { Console.WriteLine("Blob " + i + ": Rotated and aligned! (angle:" + ang + ")"); } } else { if (debug) { Console.WriteLine("Blob " + i + ": Rotation skipped by option -bnotrotate (angle:" + ang + ")"); } } //Applica filtri var filter1 = new Median(); filter1.ApplyInPlace(tmp_img_blob); var filter2 = new OtsuThreshold(); filter2.ApplyInPlace(tmp_img_blob); //Decodifica if (debug) { Console.WriteLine("Blob " + i + ": Extracted! Trying to decode..."); } BarcodeReader reader = new BarcodeReader { AutoRotate = true }; Result result = reader.Decode(tmp_img_blob); //Output Results if (result != null) { if (emulate) { stopWatch.Stop(); Console.WriteLine("Success in " + stopWatch.Elapsed); } else { Console.WriteLine(result.Text); } Environment.Exit(0); } else if (debug) { Console.WriteLine("Blob " + i + ": Decode failed! (Result null)"); } } } else { BarcodeReader reader = new BarcodeReader { AutoRotate = true }; Result result = reader.Decode(tmp_img); //Output Results if (result != null) { if (emulate) { stopWatch.Stop(); Console.WriteLine(stopWatch.Elapsed); } else { Console.WriteLine(result.Text); Environment.Exit(0); } } else if (debug) { Console.WriteLine("Decode failed! (Result null)"); } } //Exit if (emulate && stopWatch.IsRunning) { stopWatch.Stop(); Console.WriteLine("Failure in " + stopWatch.Elapsed); } Environment.Exit(0); } catch (Exception ex) { Console.WriteLine("Fatal Error: " + ex.Message + "\n" + ex.InnerException); } }
/// <summary> /// 图片处理过程 /// </summary> /// <param name="bitmap"></param> private /*Bitmap*/ void ProcessImage(Bitmap bitmap) { // lock image BitmapData bitmapData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); // step 1 - turn background to black //ColorFiltering colorFilter = new ColorFiltering(); //colorFilter.Red = new IntRange(0, 64); //colorFilter.Green = new IntRange(0, 64); //colorFilter.Blue = new IntRange(0, 64); //colorFilter.FillOutsideRange = false; //colorFilter.ApplyInPlace(bitmapData); // step 2 - locating objects BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = 5; blobCounter.MinWidth = 5; blobCounter.ProcessImage(bitmapData); Blob[] blobs = blobCounter.GetObjectsInformation(); bitmap.UnlockBits(bitmapData); // step 3 - check objects' type and highlight SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); //Bitmap test = bitmap.Save("12345.jpg", ImageFormat.Gif); Graphics g = Graphics.FromImage(CheckPixPicture(bitmap)); //Pen yellowPen = new Pen(Color.Yellow, 2); // circles Pen redPen = new Pen(Color.Red, 2); // quadrilateral //Pen brownPen = new Pen(Color.Brown, 2); // quadrilateral with known sub-type //Pen greenPen = new Pen(Color.Green, 2); // known triangle //Pen bluePen = new Pen(Color.Blue, 2); // triangle for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); AForge.Point center; float radius; // is circle ? //if (shapeChecker.IsCircle(edgePoints, out center, out radius)) //{ // //g.DrawEllipse(yellowPen, // // (float)(center.X - radius), (float)(center.Y - radius), // // (float)(radius * 2), (float)(radius * 2)); //} //else //{ List <IntPoint> corners; // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { // get sub-type PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); Pen pen; //if (subtype == polygonsubtype.unknown) //{ // pen = (corners.count == 4) ? redpen : bluepen; //} //else //{ // pen = (corners.count == 4) ? brownpen : greenpen; //} g.DrawPolygon(redPen, ToPointsArray(corners)); } //} } //yellowPen.Dispose(); redPen.Dispose(); //greenPen.Dispose(); //bluePen.Dispose(); //brownPen.Dispose(); g.Dispose(); // put new image to clipboard Clipboard.SetDataObject(bitmap); //return bitmap; }
public void findObjects(Bitmap image1, Bitmap image2) //find object(s) { BlobCounter blobCounter1 = new BlobCounter(); blobCounter1.MinWidth = 5; blobCounter1.MinHeight = 5; blobCounter1.FilterBlobs = true; blobCounter1.ObjectsOrder = ObjectsOrder.Size; //---------------------------------- BlobCounter blobCounter2 = new BlobCounter(); blobCounter2.MinWidth = 5; blobCounter2.MinHeight = 5; blobCounter2.FilterBlobs = true; blobCounter2.ObjectsOrder = ObjectsOrder.Size; BitmapData objectsData1 = image1.LockBits(new Rectangle(0, 0, image1.Width, image1.Height), ImageLockMode.ReadOnly, image1.PixelFormat); // grayscaling Grayscale grayscaleFilter1 = new Grayscale(0.2125, 0.7154, 0.0721); UnmanagedImage grayImage1 = grayscaleFilter1.Apply(new UnmanagedImage(objectsData1)); // unlock image image1.UnlockBits(objectsData1); BitmapData objectsData2 = image1.LockBits(new Rectangle(0, 0, image1.Width, image1.Height), ImageLockMode.ReadOnly, image1.PixelFormat); // grayscaling Grayscale grayscaleFilter2 = new Grayscale(0.2125, 0.7154, 0.0721); UnmanagedImage grayImage2 = grayscaleFilter2.Apply(new UnmanagedImage(objectsData2)); // unlock image image1.UnlockBits(objectsData2); blobCounter1.ProcessImage(image1); Rectangle[] rects1 = blobCounter1.GetObjectsRectangles(); Blob[] blobs1 = blobCounter1.GetObjectsInformation(); blobCounter2.ProcessImage(image2); Rectangle[] rects2 = blobCounter2.GetObjectsRectangles(); Blob[] blobs2 = blobCounter2.GetObjectsInformation(); if (rdiobtnsingleobject.Checked) { //Single object Tracking-------- Graphics g = pictureBox1.CreateGraphics(); if (rects1.Length > 0) { Rectangle objectRect1 = rects1[0]; using (Pen pen = new Pen(Color.FromArgb(252, 3, 26), 2)) { g.DrawRectangle(pen, objectRect1); } } if (rects2.Length > 0) { Rectangle objectRect2 = rects2[0]; using (Pen pen = new Pen(Color.FromArgb(252, 3, 26), 2)) { g.DrawRectangle(pen, objectRect2); } } g.Dispose(); } if (rdiobtnMultipleObjects.Checked) { //Multi tracking------- for (int i = 0; rects1.Length > i; i++) { Rectangle objectRect = rects1[i]; Graphics g = pictureBox1.CreateGraphics(); using (Pen pen = new Pen(Color.FromArgb(252, 3, 26), 2)) { g.DrawRectangle(pen, objectRect); g.DrawString((i + 1).ToString(), new Font("Arial", 12), Brushes.Red, objectRect); } int objectX = objectRect.X + (objectRect.Width / 2); int objectY = objectRect.Y + (objectRect.Height / 2); g.Dispose(); } } if (rdiobtnGeoShape.Checked) { SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); int circles = 0; int squares = 0; int triangles = 0; Graphics g = pictureBox1.CreateGraphics(); Pen yellowPen = new Pen(Color.Yellow, 2); // circles Pen redPen = new Pen(Color.Red, 2); // quadrilateral Pen brownPen = new Pen(Color.Brown, 2); // quadrilateral with known sub-type Pen greenPen = new Pen(Color.Green, 2); // known triangle Pen bluePen = new Pen(Color.Blue, 2); // triangle for (int i = 0, n = blobs1.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter1.GetBlobsEdgePoints(blobs1[i]); AForge.Point center; float radius; // is circle ? if (shapeChecker.IsCircle(edgePoints, out center, out radius)) { g.DrawEllipse(yellowPen, (float)(center.X - radius), (float)(center.Y - radius), (float)(radius * 2), (float)(radius * 2)); circles++; } else { List <IntPoint> corners; // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { // get sub-type PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners); Pen pen; if (subType == PolygonSubType.Unknown) { if (corners.Count == 4) { pen = redPen; } else { pen = bluePen; triangles++; } } else { if (corners.Count == 4) { pen = brownPen; squares++; } else { pen = greenPen; triangles++; } } g.DrawPolygon(pen, ToPointsArray(corners)); } } } g.DrawString("circles: " + circles.ToString() + " squares: " + squares.ToString() + " triangles: " + triangles.ToString(), new Font("Arial", 12), Brushes.Red, new System.Drawing.Point(0, 0)); triangles = 0; circles = 0; squares = 0; yellowPen.Dispose(); redPen.Dispose(); greenPen.Dispose(); bluePen.Dispose(); brownPen.Dispose(); g.Dispose(); } }