public void IsConvexPolygon( ) { List <IntPoint> corners; Assert.AreEqual(true, shapeChecker.IsConvexPolygon(triangle1, out corners)); Assert.AreEqual(3, corners.Count); Assert.AreEqual(true, shapeChecker.IsConvexPolygon(equilateralTriangle, out corners)); Assert.AreEqual(3, corners.Count); Assert.AreEqual(true, shapeChecker.IsConvexPolygon(isoscelesTriangle, out corners)); Assert.AreEqual(3, corners.Count); Assert.AreEqual(true, shapeChecker.IsConvexPolygon(rectangledTriangle, out corners)); Assert.AreEqual(3, corners.Count); Assert.AreEqual(true, shapeChecker.IsConvexPolygon(square1, out corners)); Assert.AreEqual(4, corners.Count); Assert.AreEqual(true, shapeChecker.IsConvexPolygon(square2, out corners)); Assert.AreEqual(4, corners.Count); Assert.AreEqual(true, shapeChecker.IsConvexPolygon(square3, out corners)); Assert.AreEqual(4, corners.Count); Assert.AreEqual(true, shapeChecker.IsConvexPolygon(rectangle, out corners)); Assert.AreEqual(4, corners.Count); Assert.AreEqual(false, shapeChecker.IsConvexPolygon(idealCicle, out corners)); Assert.AreEqual(false, shapeChecker.IsConvexPolygon(distorredCircle, out corners)); }
private bool BlobCounter() { // lock image BitmapData bitmapData = _bitmap.LockBits(ImageLockMode.ReadWrite); // 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 = 100; blobCounter.ProcessImage(bitmapData); Blob[] blobs = blobCounter.GetObjectsInformation(); _bitmap.UnlockBits(bitmapData); // step 3 - check objects' type and highlight SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); using (var g = Graphics.FromImage(_bitmap)) using (Pen pen = new Pen(Color.Red, 2)) { for (int i = 0; i < blobs.Length; i++) { //Debug.WriteLine(String.Format("Blob {0}: W: {1} H:{2} ", i, blobs[i].Rectangle.Width, blobs[i].Rectangle.Height)); List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); List <IntPoint> corners; if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; g.DrawRectangle(pen, blobs[i].Rectangle); } } } RectRight = new Rectangle(); RectLeft = new Rectangle(); if (blobs.Length != 2 || blobs.Any(b => b.Rectangle.Width > 47)) { return(false); } else { RectLeft = blobs.OrderBy(b => b.Rectangle.Left).First().Rectangle; RectRight = blobs.OrderBy(b => b.Rectangle.Left).Last().Rectangle; return(true); } }
/// <summary> /// Méthode qui analyse les images envoyées par le client /// Repère les formes présentes, les découpe et les enregistre en ficiers distincts /// </summary> public void ProcessImage() { using (CamCapturer.CamCapturer cam = new CamCapturer.CamCapturer()) { Picture = cam.GetCapture(); Copy = cam.GetCapture(); } ShapeChecker = new SimpleShapeChecker(); ShapeAnalyser = new BlobCounter(); string date = DateTime.Now.Date.ToString("dMyyyy"); FolderName = string.Format("Kuhlschrank-{0}", date); ShapeAnalyser.FilterBlobs = true; ShapeAnalyser.MinHeight = 200; ShapeAnalyser.MinWidth = 500; Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), FolderName)); BitmapData bitData = Picture.LockBits(new Rectangle(0, 0, Picture.Width, Picture.Height), ImageLockMode.ReadWrite, Picture.PixelFormat); ColorFiltering filter = new ColorFiltering(); filter.Red = new IntRange(0, 64); filter.Green = new IntRange(0, 64); filter.Blue = new IntRange(0, 64); filter.FillOutsideRange = false; filter.ApplyInPlace(bitData); ShapeAnalyser.ProcessImage(bitData); Blob[] blobs = ShapeAnalyser.GetObjectsInformation(); Picture.UnlockBits(bitData); for (int i = 0; i < blobs.Length; i++) { List <IntPoint> edgePoints = ShapeAnalyser.GetBlobsEdgePoints(blobs[i]); List <IntPoint> corners; ShapeChecker.IsConvexPolygon(edgePoints, out corners); IntPoint pt0 = corners[0]; IntPoint pt1 = corners[1]; IntPoint pt2 = corners[2]; double width = Math.Sqrt(Math.Pow(pt1.X - pt0.X, 2) + Math.Pow(pt1.Y - pt0.Y, 2)); double height = Math.Sqrt(Math.Pow(pt2.X - pt1.X, 2) + Math.Pow(pt2.Y - pt1.Y, 2)); Rectangle crop = new Rectangle(corners[0].X, corners[1].Y, (int)width + 50, (int)height + 50); Bitmap target = new Bitmap(crop.Width, crop.Height); using (Graphics gr = Graphics.FromImage(target)) gr.DrawImage(Copy, new Rectangle(0, 0, target.Width, target.Height), crop, GraphicsUnit.Pixel); target.Save(string.Format(@"{0}\{1}\crop{2}.jpg", Path.GetTempPath(), FolderName, i)); } }
public static List <Rectangle> FindRectangles(Bitmap source) { Bitmap canny = Grayscale.CommonAlgorithms.RMY.Apply(source); CannyEdgeDetector edgeDetector = new CannyEdgeDetector(5, 20); edgeDetector.ApplyInPlace(canny); BlobCounter blobCounter = new BlobCounter { FilterBlobs = true, MinWidth = 5, MinHeight = 5 }; blobCounter.ProcessImage(canny); Blob[] blobs = blobCounter.GetObjectsInformation(); List <Rectangle> rectangles = new List <Rectangle>(); SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); for (int i = 0; i < blobs.Length; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); if (shapeChecker.IsConvexPolygon(edgePoints, out List <IntPoint> corners)) { if (blobs[i].Rectangle.Width > canny.Width / 5.3 && blobs[i].Rectangle.Width <canny.Width / 4.41 && canny.Height / 10.3> blobs[i].Rectangle.Height && blobs[i].Rectangle.Height > canny.Height / 20.5) { rectangles.Add(blobs[i].Rectangle); } } } // order by descending area rectangles.Sort((a, b) => { if (a.Width * a.Height > b.Width * b.Height) { return(1); } else if (a.Width * a.Height < b.Width * b.Height) { return(-1); } return(0); }); return(rectangles); }
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 List <DetectedCard> Detect(Bitmap bitmap, out Bitmap detectionImage) { var imageTools = new ImageTools(); var detectedCards = new List <DetectedCard>(); // Greyscale var greyscaleImage = imageTools.GreyscaleEdgeDetectionImage(bitmap); var bitmapData = greyscaleImage.LockBits( new Rectangle(0, 0, greyscaleImage.Width, greyscaleImage.Height), ImageLockMode.ReadWrite, greyscaleImage.PixelFormat); var blobCounter = new BlobCounter { FilterBlobs = true, MinHeight = Convert.ToInt32(BlobHeight * scaleFactor), MinWidth = Convert.ToInt32(BlobWidth * scaleFactor) }; blobCounter.ProcessImage(bitmapData); var blobs = blobCounter.GetObjectsInformation(); greyscaleImage.UnlockBits(bitmapData); var shapeChecker = new SimpleShapeChecker(); var cardPositions = new List <IntPoint>(); // Loop through detected shapes for (var i = 0; i < blobs.Length; i++) { var edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); // is triangle or quadrilateral if (!shapeChecker.IsConvexPolygon(edgePoints, out var corners)) { continue; } var subType = shapeChecker.CheckPolygonSubType(corners); // Only return 4 corner rectanges if (subType != PolygonSubType.Parallelogram && subType != PolygonSubType.Rectangle || corners.Count != 4) { continue; } corners = RotateCard(corners); // Prevent it from detecting the same card twice if (cardPositions.Any(point => corners[0].DistanceTo(point) < Convert.ToInt32(40 * scaleFactor))) { continue; } // Hack to prevent it from detecting smaller sections of the card instead of the whole card if (GetArea(corners) < Convert.ToInt32(DetectionThreshold * scaleFactor)) { continue; } cardPositions.Add(corners[0]); var cardBitmap = imageTools.GetDetectedCardImage(corners, bitmap, scaleFactor); var card = new DetectedCard { Corners = corners, CardBitmap = cardBitmap }; detectedCards.Add(card); } detectionImage = greyscaleImage; return(detectedCards); }
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; }
private void detectQuads(Bitmap bitmap) { // Greyscale filteredBitmap = Grayscale.CommonAlgorithms.BT709.Apply(bitmap); // Contrast - try to sharpen edges //ContrastStretch filter = new ContrastStretch(); //filter.ApplyInPlace(filteredBitmap); // edge filter // This filters accepts 8 bpp grayscale images for processing //Alternatives: //DifferenceEdgeDetector edgeFilter = new DifferenceEdgeDetector(); //HomogenityEdgeDetector filter = new HomogenityEdgeDetector(); //CannyEdgeDetector filter = new CannyEdgeDetector( ); var edgeFilter = new SobelEdgeDetector(); edgeFilter.ApplyInPlace(filteredBitmap); // Threshhold filter var threshholdFilter = new Threshold(240); //180 threshholdFilter.ApplyInPlace(filteredBitmap); var bitmapData = filteredBitmap.LockBits( new Rectangle(0, 0, filteredBitmap.Width, filteredBitmap.Height), ImageLockMode.ReadWrite, filteredBitmap.PixelFormat); var blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; //possible finetuning blobCounter.MinHeight = Convert.ToInt32(int.Parse(blobHigh.Text) * fScaleFactor); //fScaleFactor blobCounter.MinWidth = Convert.ToInt32(int.Parse(blobWidth.Text) * fScaleFactor); //fScaleFactor #if DEBUG Console.WriteLine("Calculate min blobsize " + blobCounter.MinWidth + "/" + blobCounter.MinHeight); #endif blobCounter.ProcessImage(bitmapData); var blobs = blobCounter.GetObjectsInformation(); filteredBitmap.UnlockBits(bitmapData); var shapeChecker = new SimpleShapeChecker(); var bm = new Bitmap(filteredBitmap.Width, filteredBitmap.Height, PixelFormat.Format24bppRgb); var g = Graphics.FromImage(bm); g.DrawImage(filteredBitmap, 0, 0); var pen = new Pen(Color.Red, 5); var cardPositions = new List <IntPoint>(); // Loop through detected shapes for (int i = 0, n = blobs.Length; i < n; i++) { var edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); List <IntPoint> corners; var sameCard = false; // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { // get sub-type var 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 (var point in cardPositions) { if (corners[0].DistanceTo(point) < Convert.ToInt32(40 * fScaleFactor)) //fScaleFactor { sameCard = true; } } if (sameCard) { continue; } /* * This code seems to have an issue if scaled up with the factor: */ // Hack to prevent it from detecting smaller sections of the card instead of the whole card if (GetArea(corners) < Convert.ToInt32(double.Parse(treasholdBox.Text) * fScaleFactor) ) //fScaleFactor { continue; } cardPositions.Add(corners[0]); g.DrawPolygon(pen, ToPointsArray(corners)); // Extract the card bitmap // Debug //var transformFilter = new QuadrilateralTransformation(corners, 600, 800); var transformFilter = new QuadrilateralTransformation(corners, Convert.ToInt32(211 * fScaleFactor), Convert.ToInt32(298 * fScaleFactor)); cardBitmap = transformFilter.Apply(cameraBitmap); var card = new MagicCard(); card.corners = corners; card.cardBitmap = cardBitmap; card.cardArtBitmap = cardArtBitmap; magicCards.Add(card); pen.Dispose(); g.Dispose(); filteredBitmap = bm; return; } } } pen.Dispose(); g.Dispose(); filteredBitmap = bm; }
private Bitmap detectQuads(Bitmap bitmap) { var cardArtBitmap = bitmap; try { /* * This code works and crops well on 80% of the images but we need 100% * */ var width = bitmap.Width + bitmap.Width / 2; var height = bitmap.Height + bitmap.Height / 2; // Create a compatible bitmap var dest = new Bitmap(width, height, bitmap.PixelFormat); var gd = Graphics.FromImage(dest); dest.Dispose(); gd.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height); // Greyscale filteredBitmap = Grayscale.CommonAlgorithms.BT709.Apply(bitmap); // Contrast //ContrastStretch filter = new ContrastStretch(); //filter.ApplyInPlace(filteredBitmap); var cutMargin = 80; // split the image to avoid the textbox beeing detected var cropFilterPre = new Crop(new Rectangle(0, cutMargin, filteredBitmap.Width, filteredBitmap.Height / 100 * 60)); filteredBitmap = cropFilterPre.Apply(filteredBitmap); // edge filter var edgeFilter = new SobelEdgeDetector(); // edgeFilter.ApplyInPlace(filteredBitmap); // Threshhold filter var threshholdFilter = new Threshold(190); threshholdFilter.ApplyInPlace(filteredBitmap); var bitmapData = filteredBitmap.LockBits( new Rectangle(0, 0, filteredBitmap.Width, filteredBitmap.Height), ImageLockMode.ReadWrite, filteredBitmap.PixelFormat); var blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = 200; blobCounter.MinWidth = 200; blobCounter.ProcessImage(bitmapData); var blobs = blobCounter.GetObjectsInformation(); filteredBitmap.UnlockBits(bitmapData); var shapeChecker = new SimpleShapeChecker(); /*var bm = new Bitmap(filteredBitmap.Width, filteredBitmap.Height, PixelFormat.Format24bppRgb); * * var g = Graphics.FromImage(bm); * g.DrawImage(filteredBitmap, 0, 0); * * var pen = new Pen(Color.Red, 5); * //var cardPositions = new List<IntPoint>();*/ // Loop through detected shapes for (int i = 0, n = blobs.Length; i < n; i++) { var edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); List <IntPoint> corners; var sameCard = false; // is triangle or quadrilateral if (shapeChecker.IsConvexPolygon(edgePoints, out corners)) { // get sub-type var subType = shapeChecker.CheckPolygonSubType(corners); // Only return 4 corner rectanges if ((subType == PolygonSubType.Parallelogram || subType == PolygonSubType.Rectangle) && corners.Count == 4) { // Hack to prevent it from detecting smaller sections of the card instead of the art if (GetArea(corners) < 120000) { continue; } //debug crap /*Bitmap newImage = filteredBitmap; * Random rnd = new Random(); * newImage.Save(@"X:\" + rnd.Next() + ".jpg", ImageFormat.Jpeg);*/ var x = corners[0].X; var y = corners[0].Y + cutMargin; var x2 = corners[2].X - corners[0].X; var y2 = corners[2].Y - (corners[0].Y + 0); if (x2 < 0 || y2 < 0) { x = corners[1].X; y = corners[1].Y + cutMargin; x2 = corners[3].X - corners[1].X; y2 = corners[3].Y - (corners[1].Y + 0); } var cropframe = new Rectangle(x, y, x2, y2); var gbfilter = new GaussianBlur(1, 5); gbfilter.ApplyInPlace(bitmap); var cropFilter = new Crop(cropframe); cardArtBitmap = cropFilter.Apply(bitmap); bitmap.Dispose(); // pen.Dispose(); // g.Dispose(); gd.Dispose(); filteredBitmap.Dispose(); return(cardArtBitmap); } } } Console.WriteLine("Fallback Triggered!"); var gfilter = new GaussianBlur(1, 5); gfilter.ApplyInPlace(bitmap); //Fallback default crop, assumes XLHQ CCGHQ images var cropFilterFallback = new Crop(new Rectangle(88, 121, 564, 440)); cardArtBitmap = cropFilterFallback.Apply(bitmap); bitmap.Dispose(); //pen.Dispose(); //g.Dispose(); gd.Dispose(); filteredBitmap.Dispose(); } catch (Exception e) { throw; } return(cardArtBitmap); }
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(); } }
// 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); }
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 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; }
private void ParseImage(int imageId) { DateTime startTime = DateTime.Now; labelDetection.Text = ""; string difImagePath = ""; if (imageId >= 0) { difImagePath = DifBoardImages[imageId]; } Bitmap orig; Bitmap dif; try { orig = (Bitmap)Bitmap.FromFile(OriginalBoardImage); if (imageId >= 0) { dif = (Bitmap)Bitmap.FromFile(difImagePath); } else { dif = (Bitmap)pictureBoxGenerated.Image; } } catch { // kill any exception due to missing files return; } pictureBoxOrig.Image = dif; Difference filter = new Difference(orig); dif = filter.Apply(dif); BlobCounter blobCounter = new BlobCounter(); blobCounter.ProcessImage(dif); Blob[] blobs = blobCounter.GetObjectsInformation(); // create Graphics object to draw on the image and a pen Graphics g = Graphics.FromImage(dif); Pen redPen = new Pen(Color.Red, 3); Pen bluePen = new Pen(Color.Blue, 1); SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); // check each object and draw circle around objects, which // are recognized as circles for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); labelDetection.Text = string.Format("{0} points", edgePoints.Count); if (edgePoints.Count <= 1) { continue; } List <IntPoint> points = new List <IntPoint>(); if (shapeChecker.IsQuadrilateral(edgePoints)) { labelDetection.Text += ", quadrilateral"; } else if (shapeChecker.IsConvexPolygon(edgePoints, out points)) { labelDetection.Text += ", convex poligon"; } else if (shapeChecker.IsTriangle(edgePoints, out points)) { labelDetection.Text += ", triangle"; } Pen usePen = shapeChecker.IsQuadrilateral(edgePoints) ? redPen : bluePen; int centerX = edgePoints[0].X; int centerY = edgePoints[0].Y; int minX = centerX; int minY = centerY; int maxX = centerX; int maxY = centerY; for (int j = 0; j < edgePoints.Count - 1; j++) { centerX += edgePoints[j + 1].X; centerY += edgePoints[j + 1].Y; if (edgePoints[j + 1].X < minX) { minX = edgePoints[j + 1].X; } if (edgePoints[j + 1].Y < minY) { minY = edgePoints[j + 1].Y; } if (edgePoints[j + 1].X > maxX) { maxX = edgePoints[j + 1].X; } if (edgePoints[j + 1].Y > maxX) { maxX = edgePoints[j + 1].Y; } g.DrawLine(usePen, edgePoints[j].X, edgePoints[j].Y, edgePoints[j + 1].X, edgePoints[j + 1].Y); } g.DrawLine(usePen , edgePoints[0].X, edgePoints[0].Y , edgePoints[edgePoints.Count - 1].X, edgePoints[edgePoints.Count - 1].Y); labelDetectedPosition.Text = string.Format("{0}, {1}" , new object[] { (centerX / edgePoints.Count), (centerY / edgePoints.Count) //, maxX - minX, maxY - minY }); labelDetectionOffset.Text = string.Format("{0}, {1}" , Grigore.Position.X - (centerX / edgePoints.Count) , Grigore.Position.Y - (centerY / edgePoints.Count) ); } redPen.Dispose(); bluePen.Dispose(); g.Dispose(); pictureBoxRoboBoard.Image = dif; labelDetection.Text = string.Format("{1}, {0} sec", (DateTime.Now - startTime), labelDetection.Text); }
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 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); }
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); }
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 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 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(); }
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); } }
private void DrawRectangle() { _blobCounter.ProcessImage(_bitmapData); var rectangles = _blobCounter.GetObjectsRectangles(); var blobs = _blobCounter.GetObjectsInformation(); //View.Canvas.Children.Clear(); foreach (var blob in blobs) { var edges = _blobCounter.GetBlobsEdgePoints(blob); List <IntPoint> corners; if (_shapeChecker.IsConvexPolygon(edges, out corners)) { var line = new System.Windows.Shapes.Line { X1 = corners[1].X, Y1 = corners[1].Y, X2 = corners[2].X, Y2 = corners[2].Y, Stroke = Brushes.Blue, StrokeThickness = 2 }; _depth = 850; var pixelWidth = Math.Abs(corners[1].X - corners[2].X); var realWidth = Math.Abs(DepthToWorld(corners[1].X, _depth) - DepthToWorld(corners[2].X, _depth)); var realWidth2 = Math.Abs(DepthToWorld(pixelWidth, _depth)); Debug.WriteLine("Real Width {0}, Real Width 2 {1}, Pixel Width: {2}, Depth: {3}", realWidth, realWidth2, pixelWidth, _depth); /*var mmWidth = (pixelWidth * 25.4) / 96; * var realMMWidth = Math.Tan(28.5) * 2 * 650 * pixelWidth; * * var zMeters = 650.0 / 1000.0; * var a = 6 - 2; * var b = corners[1].X - (639 / 2); * var c = Math.Tan(57 / 2); * var d = zMeters / 640; * var x1Meters = a * (corners[1].X - (639 / 2)) * c * d; * var x2Meters = a * (corners[2].X - (639 / 2)) * c * d; * var diff = Math.Abs(x1Meters - x2Meters);*/ var polygon = new Polygon { Stroke = Brushes.Red, StrokeThickness = 2, Points = new PointCollection(corners.ToPoints()) }; /*View.Canvas.Children.Add(polygon); * View.Canvas.Children.Add(line);*/ } } /*View.Canvas.Children.Clear(); * * foreach (var rectangle in rectangles) * { * var rect = new Rectangle * {Width = rectangle.Width, Height = rectangle.Height, Stroke = Brushes.Red, StrokeThickness = 2}; * * Canvas.SetLeft(rect, rectangle.X); * Canvas.SetTop(rect, rectangle.Y); * * View.Canvas.Children.Add(rect); * } * * Console.WriteLine();*/ /*var bitmap = new BitmapReader(imageWidth, imageHeight, pixelData); * var edges = new List<Point>();*/ /*for (var y = 0; y < imageHeight; y++) * { * for (var x = 0; x < imageWidth; x++) * { * if (bitmap.IsFill(x, y)) * { * edges.Add(new Point(x, y)); * } * } * }*/ /*var bitmap = new System.Drawing.Bitmap(imageWidth, imageHeight, PixelFormat.Format32bppRgb); * * for (var y = 0; y < imageHeight; y++) * { * for (var x = 0; x < imageWidth; x++) * { * var index = y * imageWidth + x; * * var r = pixelData[index + RedIndex]; * var g = pixelData[index + GreenIndex]; * var b = pixelData[index + BlueIndex]; * * bitmap.SetPixel(x, y, System.Drawing.Color.FromArgb(r, g, b)); * } * } * * _blobCounter.ProcessImage(bitmap); * * var blobs = _blobCounter.GetObjectsInformation(); * * var streamGeometry = new StreamGeometry(); * * using (var geometryContext = streamGeometry.Open()) * { * foreach (var blob in blobs) * { * var edgePoint = _blobCounter.GetBlobsEdgePoints(blob); * List<IntPoint> corners; * * if (_shapeChecker.IsConvexPolygon(edgePoint, out corners)) * { * var subType = _shapeChecker.CheckPolygonSubType(corners); * * geometryContext.BeginFigure(corners[0].ToPoint(), false, true); * geometryContext.PolyLineTo(corners.ToPoints(), true, true); * } * } * * Console.WriteLine(); * } * * var drawingVisual = new DrawingVisual(); * * using (var drawingContext = drawingVisual.RenderOpen()) * { * drawingContext.DrawGeometry(Brushes.Red, new Pen(Brushes.Gold, 2), streamGeometry); * } * * View.Graphics.Add(drawingVisual);*/ }
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; }
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(); }
private void ParseImage(int imageId) { DateTime startTime = DateTime.Now; Console.WriteLine(string.Format("Start parsing {0}", startTime)); string difImagePath = ""; if (imageId >= 0) { difImagePath = DifBoardImages[imageId]; } Bitmap orig; Bitmap dif; try { Console.WriteLine("Load files"); orig = (Bitmap)Bitmap.FromFile(OriginalBoardImage); if (imageId >= 0) { dif = (Bitmap)Bitmap.FromFile(difImagePath); } else { dif = (Bitmap)internalImageContainer; } } catch (Exception ex) { Console.WriteLine("ERR: " + ex.Message); Console.WriteLine(ex.StackTrace); // kill any exception due to missing files return; } Difference filter = new Difference(orig); dif = filter.Apply(dif); Console.WriteLine("Apply difference filter"); BlobCounter blobCounter = new BlobCounter(); blobCounter.ProcessImage(dif); Console.WriteLine("Blob counting"); Blob[] blobs = blobCounter.GetObjectsInformation(); // create Graphics object to draw on the image and a pen Graphics g = Graphics.FromImage(dif); Pen redPen = new Pen(Color.Red, 3); Pen bluePen = new Pen(Color.Blue, 1); SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); // check each object and draw circle around objects, which // are recognized as circles for (int i = 0, n = blobs.Length; i < n; i++) { List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]); Console.Write(string.Format("Detected {0} points", edgePoints.Count)); if (edgePoints.Count <= 1) { continue; } List <IntPoint> points = new List <IntPoint>(); if (shapeChecker.IsQuadrilateral(edgePoints)) { Console.Write(", quadrilateral"); } else if (shapeChecker.IsConvexPolygon(edgePoints, out points)) { Console.Write(", convex poligon"); } else if (shapeChecker.IsTriangle(edgePoints, out points)) { Console.Write(", triangle"); } Pen usePen = shapeChecker.IsQuadrilateral(edgePoints) ? redPen : bluePen; int centerX = edgePoints[0].X; int centerY = edgePoints[0].Y; for (int j = 0; j < edgePoints.Count - 1; j++) { centerX += edgePoints[j + 1].X; centerY += edgePoints[j + 1].Y; g.DrawLine(usePen, edgePoints[j].X, edgePoints[j].Y, edgePoints[j + 1].X, edgePoints[j + 1].Y); } // add last point centerX += edgePoints[edgePoints.Count - 1].X; centerY += edgePoints[edgePoints.Count - 1].Y; g.DrawLine(usePen , edgePoints[0].X, edgePoints[0].Y , edgePoints[edgePoints.Count - 1].X, edgePoints[edgePoints.Count - 1].Y); Console.WriteLine(string.Format("\nOriginal (x, y): {0}, {1}" , new object[] { (centerX / edgePoints.Count), (centerY / edgePoints.Count) })); Console.WriteLine(string.Format("Detected (x, y): {0}, {1}" , (centerX / edgePoints.Count) , (centerY / edgePoints.Count) )); } redPen.Dispose(); bluePen.Dispose(); g.Dispose(); //DifI = dif; dif.Save(dirPath + "processed-dif.jpg"); Console.WriteLine(string.Format("Duration: {0} sec", (DateTime.Now - startTime))); }
// Process image private void ProcessImage(Bitmap bitmap) { // lock image var bitmapData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); // step 1 - turn background to black var colorFilter = new ColorFiltering { Red = new IntRange(0, 64), Green = new IntRange(0, 64), Blue = new IntRange(0, 64), FillOutsideRange = false }; colorFilter.ApplyInPlace(bitmapData); // step 2 - locating objects var blobCounter = new BlobCounter { FilterBlobs = true, MinHeight = 5, MinWidth = 5 }; blobCounter.ProcessImage(bitmapData); var blobs = blobCounter.GetObjectsInformation(); bitmap.UnlockBits(bitmapData); // step 3 - check objects' type and highlight var shapeChecker = new SimpleShapeChecker(); var g = Graphics.FromImage(bitmap); var yellowPen = new Pen(Color.Yellow, 2); // circles var redPen = new Pen(Color.Red, 2); // quadrilateral var brownPen = new Pen(Color.Brown, 2); // quadrilateral with known sub-type var greenPen = new Pen(Color.Green, 2); // known triangle var bluePen = new Pen(Color.Blue, 2); // triangle for (int i = 0, n = blobs.Length; i < n; i++) { var 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 var 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; UpdatePictureBoxPosition(); }
// 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; } } }
/// <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(); } }