I am trying to detect Circle inside Rectangle in AForge. I have successfully determined Rectangles but unable to find circles inside Rectangle. How to find shape inside another shape in AForge.
string strPath = Server.MapPath("~/Recipt001.png");
Bitmap myBitmap = new Bitmap(strPath);
//Some filters Grayscale, invert, threshold
//Blod Filtering
BlobCounter blobCounter = new BlobCounter();
blobCounter.ProcessImage(temp);
blobCounter.ObjectsOrder = ObjectsOrder.YX;
blobCounter.FilterBlobs = true;
Blob[] blobs = blobCounter.GetObjectsInformation();
Graphics g = Graphics.FromImage(myBitmap);
Pen redPen = new Pen(Color.Red, 2);
SimpleShapeChecker shapeChecker = new SimpleShapeChecker();
// dictionary of color to highlight different shapes
Dictionary<PolygonSubType, Color> colors = new Dictionary<PolygonSubType, Color>();
colors.Add(PolygonSubType.Unknown, Color.White);
colors.Add(PolygonSubType.Trapezoid, Color.Orange);
colors.Add(PolygonSubType.Parallelogram, Color.Red);
colors.Add(PolygonSubType.Rectangle, Color.Green);
colors.Add(PolygonSubType.Square, Color.Blue);
colors.Add(PolygonSubType.Rhombus, Color.Gray);
colors.Add(PolygonSubType.EquilateralTriangle, Color.Pink);
colors.Add(PolygonSubType.IsoscelesTriangle, Color.Purple);
colors.Add(PolygonSubType.RectangledTriangle, Color.SkyBlue);
colors.Add(PolygonSubType.RectangledIsoscelesTriangle, Color.SeaGreen);
for (int i = 0, n = blobs.Length; i < n; i++)
{
List<IntPoint> corners;
List<IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);
Point center;
double radius;
if (shapeChecker.IsQuadrilateral(edgePoints, out corners))
{
if (shapeChecker.CheckPolygonSubType(corners) == PolygonSubType.Rectangle)
{
g.DrawPolygon(redPen, ToPointsArray(corners));
}
}
}
redPen.Dispose();
g.Dispose();
None of image processing libraries and even image processing in MATLAB lets you search ROI inside ROI (ROI - region of intrest like rectangles or circles). Concept is CROP REGION -> SEARCH OBJECTS IN REGION
So first locate primary rectangles, thereafter crop image to rectangles and perform circle search inside them. Otherwise search for all circles and all rectangles and then classify circles to be belonging to which rectangle using simple maths.
Related
I have an app that will draw many shapes (rectangle, line and circle) on a panel.
the panel can zoom in and out this shapes.
What I'm trying to do is when the application is fired I need to have the shapes zoomed to fit the window.
How I can do that, I read a lot about defined Images but not shapes.
here is my snap shot
private void panel1_Paint(object sender, PaintEventArgs e)
{
SolidBrush brushs = new SolidBrush(Color.White);
e.Graphics.Clip = new Region(new Rectangle(0, 0, Viewer.Width, Viewer.Height));
e.Graphics.FillRegion(brushs, e.Graphics.Clip);
Graphics g = e.Graphics;
g.TranslateTransform(_ImgX, _ImgY);
g.ScaleTransform(_Zoom, _Zoom);
g.SmoothingMode = SmoothingMode.AntiAlias;
SolidBrush myBrush = new SolidBrush(Color.Black);
Pen p = new Pen(Color.Red);
foreach (CircuitData.ResistorRow resistorRow in ResistorData.Resistor)
{
RectangleF rec = new RectangleF((float)(resistorRow.CenterX - resistorRow.Length/ 2), (float)(resistorRow.CenterY - resistorRow.Width/ 2), (float)resistorRow.Length, (float)resistorRow.Width);
float orientation = 360 - (float)resistorRow.Orientation;
PointF center = new PointF((float)resistorRow.CenterX, (float)resistorRow.CenterY);
PointF[] points = CreatePolygon(rec, center, orientation);
if (!Double.IsNaN(resistorRow.HiX) && !Double.IsNaN(resistorRow.HiY))
{
g.FillEllipse(myBrush, (float)resistorRow.HiX - 2 , (float)resistorRow.HiY - 2, 4, 4);
g.DrawLine(p, new PointF((float)resistorRow.HiX , (float)resistorRow.HiY ), center);
}
g.FillPolygon(myBrush, points);
}
}
Thanks
Draw your shapes onto a Metafile. Its dimensions will be calculated automatically after it is created. At the end you can zoom it safely when you draw it onto the panel.
// the reference Graphics can be taken from your form, its size does not matter
Graphics refGraph = this.CreateGraphics();
IntPtr hdc = refGraph.GetHdc();
Metafile result = new Metafile(hdc, EmfType.EmfOnly, "Shapes");
using (var g = Graphics.FromImage(result))
{
// draw your shapes here (zooming is not necessary)
DrawShapes(g);
}
refGraph.ReleaseHdc(hdc);
refGraph.Dispose();
// use this metafile on the panel
return result;
I want to find small black squares/rectangles in scanned sheet to:
deskewing image if needed.
remove white page margin.
Input image:
sample image 1 http://us.cdn.persiangig.com/preview/ii2jf6/2.jpg
Output image:
sample image 2 http://us.cdn.persiangig.com/preview/9ntpnc/1.jpg
My code to find square is:
Bitmap pic =(Bitmap) pictureBox1.Image;
// create filter
AForge.Imaging.Filters.Median Medianfilter = new AForge.Imaging.Filters.Median();
// apply the filter
Medianfilter.ApplyInPlace(pic);
Bitmap grayImage;
if (pic.PixelFormat != PixelFormat.Format16bppGrayScale && pic.PixelFormat != PixelFormat.Format8bppIndexed)
{
AForge.Imaging.Filters.Grayscale grayscalefilter = new AForge.Imaging.Filters.Grayscale(0.2125, 0.7154, 0.0721);
grayImage = grayscalefilter.Apply((Bitmap)pictureBox1.Image);
}
else
{
grayImage = pic;
}
// black & white:
Threshold(ref grayImage, Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox1.Text));
// invert filter
Invert invertfilter = new Invert();
// apply the filter
invertfilter.ApplyInPlace(grayImage);
// Edge Detector filter
DifferenceEdgeDetector EdgeDetectorfilter = new DifferenceEdgeDetector();
// apply the filter
EdgeDetectorfilter.ApplyInPlace(grayImage);
// create filter
Dilatation Dilatationfilter = new Dilatation();
// apply the filter
Dilatationfilter.ApplyInPlace(grayImage);
Finding object(square/rectangle) in image:
// lock image
BitmapData bitmapData = grayImage.LockBits(new Rectangle(0, 0, grayImage.Width, grayImage.Height),
ImageLockMode.ReadWrite, grayImage.PixelFormat);
// step 2 - locating objects
BlobCounter blobCounter = new BlobCounter();
blobCounter.FilterBlobs = true;
blobCounter.MinHeight = 10; //*-*-*-*-
blobCounter.MinWidth = 10;
blobCounter.MaxHeight = 50;
blobCounter.MaxWidth = 50;
blobCounter.ProcessImage(bitmapData);
Blob[] blobs = blobCounter.GetObjectsInformation();
grayImage.UnlockBits(bitmapData);
// step 3 - check objects' type and highlight
SimpleShapeChecker shapeChecker = new SimpleShapeChecker();
Graphics g = Graphics.FromImage(pic);
Pen redPen = new Pen(Color.Red, 2); // quadrilateral
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]);
List<IntPoint> corners;
// is triangle or quadrilateral
if (shapeChecker.IsQuadrilateral(edgePoints, out corners))
{
// get sub-type
PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners);
Pen pen;
if (subType == PolygonSubType.Square)
{
pen = (corners.Count == 4) ? bluePen : redPen;
g.DrawPolygon(pen, ToPointsArray(corners));
}
}
}
redPen.Dispose();
bluePen.Dispose();
g.Dispose();
pictureBox1.Image = pic;
Problem is low accuracy on detecting squares and rectangles!!!
How can I solve this problem?
If you can use OpenCV this is quite easy. Use the Hough transform and find peaks in the output. Those correspond to straight lines in your input.
If you can't use OpenCV, you'll need to implement it yourself. Here's something to get you started.
https://en.wikipedia.org/?title=Hough_transform
EDIT
As Anders Gustafsson points out in the comment below, the Hough Transform is available in AForge for .NET so implementing it yourself isn't a necessity.
http://www.aforgenet.com/framework/features/hough_transformation.html
I am using croppic to crop images. Is there any possibility to extend its functionality to rotate the image, before sending it to crop. Something like this
var angle = 0;
$('#button').on('click', function() {
angle += 90;
$("#image").rotate(angle);
});
Here is the demo
I can manage to to rotate the image, but the cropped image is not in rotated position. Any idea?
Update:
Now the image is getting rotated. I have managed to keep rotated image by the same handler that uses crop method. But the cropped image in rotated position occurs only when the rotated image is in 180 rotation. When its in the 90/270, the image, obviously don't fit in the bounding box (if you have seen croppic) and I get a MemoryOutOfBound exception.
Here is the code:
public static Bitmap RotateImage(Bitmap bmpSrc, float theta)
{
Matrix mRotate = new Matrix();
mRotate.Translate(bmpSrc.Width / -2, bmpSrc.Height / -2, MatrixOrder.Append);
mRotate.RotateAt(theta, new System.Drawing.Point(0, 0), MatrixOrder.Append);
using (GraphicsPath gp = new GraphicsPath())
{ // transform image points by rotation matrix
gp.AddPolygon(new System.Drawing.Point[] { new System.Drawing.Point(0, 0), new System.Drawing.Point(bmpSrc.Width, 0), new System.Drawing.Point(0, bmpSrc.Height) });
gp.Transform(mRotate);
System.Drawing.PointF[] pts = gp.PathPoints;
// create destination bitmap sized to contain rotated source image
Rectangle bbox = boundingBox(bmpSrc, mRotate);
Bitmap bmpDest = new Bitmap(bbox.Width, bbox.Height);
using (Graphics gDest = Graphics.FromImage(bmpDest))
{ // draw source into dest
Matrix mDest = new Matrix();
mDest.Translate(bmpDest.Width / 2, bmpDest.Height / 2, MatrixOrder.Append);
gDest.Transform = mDest;
gDest.DrawImage(bmpSrc, pts);
return bmpDest;
}
}
}
private static Rectangle boundingBox(Image img, Matrix matrix)
{
GraphicsUnit gu = new GraphicsUnit();
Rectangle rImg = Rectangle.Round(img.GetBounds(ref gu));
// Transform the four points of the image, to get the resized bounding box.
System.Drawing.Point topLeft = new System.Drawing.Point(rImg.Left, rImg.Top);
System.Drawing.Point topRight = new System.Drawing.Point(rImg.Right, rImg.Top);
System.Drawing.Point bottomRight = new System.Drawing.Point(rImg.Right, rImg.Bottom);
System.Drawing.Point bottomLeft = new System.Drawing.Point(rImg.Left, rImg.Bottom);
System.Drawing.Point[] points = new System.Drawing.Point[] { topLeft, topRight, bottomRight, bottomLeft };
GraphicsPath gp = new GraphicsPath(points,new byte[] { (byte)PathPointType.Start,
(byte)PathPointType.Line, (byte)PathPointType.Line,
(byte)PathPointType.Line });
gp.Transform(matrix);
return Rectangle.Round(gp.GetBounds());
}
I think main issue is in the bounding box.
using (Bitmap rotate = new Bitmap(RotateImage(bmp, rotateAngle)))
{
using (Bitmap cloneRotate = (Bitmap)rotate.Clone()) //getting error here
{
//some stuffs
cloneRotate.save(mycroppedimageurl);
}
}
I'm wondering if that's possible:
I got a c# application with something like a display consisting of about 11000 circles drawn on the Form.
What I want to achieve is to be able to draw text on that display, but not using the "real" pixels, but using the circles (rectangles) drawn on the form as pixels.
Edit 1:
When drawing text in c#, you would i.e. use something like Graphics.DrawString(...), giving the method a rectangle (so coordinates) in which the text should be drawn in. That text then is drawn in that rectangle using the screen pixels. What I want to do is draw text as well but not using the screen pixels but my custom pixels of which my display consists.
Edit 2
Method used to draw the circles on the Form; Circles is a list consisting of Circle objects, where circleRectangle returns the coordinates in which the circle should be drawn and Filled tells the method if the circle should be filled or not.
public void DrawCircles(Graphics g)
{
graphics = g;
graphics.SmoothingMode =System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
Pen pen = new Pen(Color.Black, penthickness);
SolidBrush brush = new SolidBrush(Color.White);
for (int j = 0; j < Circles.Count;j++ )
{
graphics.DrawEllipse(pen, Circles[j].CircleRectangle);
if (Circles[j].Filled)
brush.Color = fillColor;
else
brush.Color = Color.White;
graphics.FillEllipse(brush, Circles[j].CircleRectangle);
}
}
Is this possible and if yes, how would I do that?
You could write on an invisible BitMap with the DrawText method and then scan the bitmap's pixels and turn the corresponding circles on.
Did that last week with the cells of DataGridView. Real easy.
Here is some code:
public void drawText(string text, Font drawFont)
{
Bitmap bmp = new Bitmap(canvasWidth, canvasHeight);
Graphics G = Graphics.FromImage(bmp);
SolidBrush brush = new SolidBrush(paintColor);
Point point = new Point( yourOriginX, yourOriginY );
G.DrawString(text, drawFont, brush, point);
for (int x = 0; x < canvasWidth; x++)
for (int y = 0; y < canvasHeight; y++)
{
Color pix = bmp.GetPixel(x, y);
setCell(x, y, pix); //< -- set your custom pixels here!
}
bmp.Dispose();
brush.Dispose();
G.Dispose();
}
Edit: You would use your dimensions and your origin for the DrawString, of course
I have a panel on which I'm drawing lines using:
Point PreviousPoint = new Point (0,0);
Point NewPoint = new Point (10,10);
Pen MyPen = new Pen(Color.Black, 2);
Graphics MyGraphics = panel1.CreateGraphics();
MyGraphics.DrawLine(MyPen, PreviousPoint, NewPoint);
This all works fine. I obviously change the points to draw more lines, but that doesn't matter for this question. I want to export that panel as a jpg file. I'm using this code:
Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(bmp, new Rectangle(0, 0, panel1.Width, panel1.Height));
bmp.Save("C:\\panel.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
This outputs a blank jpg. The background of my panel is gray, and the background of the jpg is the same gray, so I know it's actually exporting the panel. Also, I added a button into the panel just to see if it would get saved, and it did. So for some reason the jpg isn't saving the lines being drawn.
So I made a workaround that solves the core problem. I made an array of the points I plotted to draw the lines, then I did this:
// make sure you actually drew something
if (MyLines.Length > 0)
{
// instantiate the stuff you need
Image img = new Bitmap(panel1.Width, panel1.Height);
Graphics g = Graphics.FromImage(img);
Pen pen = new Pen(Color.Black, 2);
// draw every line (from every even index to the one after it)
for (int i = 0; i < MyLines.Length; i++)
{
if (i % 2 == 0)
{
g.DrawLine(pen, MyLines[i], MyLines[i + 1]);
}
}
img.Save("C:\\panel.png", System.Drawing.Imaging.ImageFormat.Png);
}
}