Polygon find the shortest way from start to end - c#

I am searching the shortest way in my polygon (route). It starts on the center border on bottom left (blue) and ends on the center border on the top right (red). It is not allowed to leave the route.
Which algorithm i can use to calculate this route? I need a list of points to draw the shortest way. A example code would be great.
Example of my polygon with start and end
var points = new List<Point> { new Point(210, 540), new Point(330, 420), new Point(360, 420), new Point(420, 390), new Point(450, 330), new Point(480, 315), new Point(510, 270), new Point(570, 240), new Point(630, 240), new Point(690, 180), new Point(750, 150), new Point(810, 120), new Point(864, 120), new Point(864, 60), new Point(810, 60), new Point(750, 90), new Point(690, 120), new Point(630, 150), new Point(570, 150), new Point(510, 210), new Point(480, 255), new Point(450, 270), new Point(420, 330), new Point(360, 360), new Point(330, 360), new Point(156, 480) };
var image = new Bitmap(1000, 600);
using (var graphics = Graphics.FromImage(image))
{
graphics.Clear(Color.White);
graphics.FillPie(Brushes.Blue, 190, 500, 10, 10, 0, 360);
graphics.FillPie(Brushes.Red, 840, 80, 10, 10, 0, 360);
graphics.DrawPolygon(new Pen(Color.Black, 2), points.ToArray());
}
image.Save("example.bmp");

Solution
Thanks #gusman
Add Raster
Calculate distance between points
Search best route with Dijkstra.NET
using Dijkstra.NET.Contract;
using Dijkstra.NET.Model;
using Dijkstra.NET.ShortestPath;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace Test.Polygon
{
class Program
{
static void Main(string[] args)
{
var points = new List<Point> { new Point(210, 540), new Point(330, 420), new Point(360, 420), new Point(420, 390), new Point(450, 330), new Point(480, 315), new Point(510, 270), new Point(570, 240), new Point(630, 240), new Point(690, 180), new Point(750, 150), new Point(810, 120), new Point(864, 120), new Point(864, 60), new Point(810, 60), new Point(750, 90), new Point(690, 120), new Point(630, 150), new Point(570, 150), new Point(510, 210), new Point(480, 255), new Point(450, 270), new Point(420, 330), new Point(360, 360), new Point(330, 360), new Point(156, 480) };
var start = new Point(190, 500);
var target = new Point(840, 80);
var image = new Bitmap(1000, 600);
using (var graphics = Graphics.FromImage(image))
{
graphics.Clear(Color.White);
graphics.FillPie(Brushes.Blue, 190, 500, 10, 10, 0, 360);
graphics.FillPie(Brushes.Red, 840, 80, 10, 10, 0, 360);
graphics.DrawPolygon(new Pen(Color.Black, 2), points.ToArray());
}
var path = new GraphicsPath(FillMode.Winding);
path.AddPolygon(points.ToArray());
var pointsForConnect = DrawRaster(5, image, path);
var dictionary = new Dictionary<uint, Point>();
dictionary.Add(0, start);
dictionary.Add(1, target);
var graph = new Graph<int, string>();
var i = 2;
foreach (var point in pointsForConnect)
{
dictionary.Add((uint)i, point);
graph.AddNode(i);
i++;
}
foreach (var point in dictionary)
{
foreach (var point2 in dictionary)
{
if (point.Equals(point2))
{
continue;
}
double dist = Math.Sqrt(Math.Pow(point2.Value.X - point.Value.X, 2) + Math.Pow(point2.Value.Y - point.Value.Y, 2));
if (dist > 50)
{
continue;
}
graph.Connect(point.Key, point2.Key, (int)dist, null);
//graph.Connect()
}
}
var dijkstra = new Dijkstra<int, string>(graph);
IShortestPathResult result = dijkstra.Process(0, 1); //result contains the shortest path
var shortestRouteIds = result.GetPath();
var shortestRoutePoints = new List<Point>();
foreach(var x in shortestRouteIds)
{
shortestRoutePoints.Add(dictionary[x]);
}
DrawDriver(shortestRoutePoints, image);
image.Save("example.bmp");
}
private static void DrawDriver(List<Point> points, Bitmap image)
{
var pen = new Pen(Color.LightGreen, 5);
for (var i = 0; i < points.Count - 1; i++)
{
var x = points[i].X;
var y = points[i].Y;
var x1 = points[i + 1].X;
var y1 = points[i + 1].Y;
DrawLineInt(image, new Point(x, y), new Point(x1, y1), pen);
}
}
private static void DrawLineInt(Bitmap bmp, Point p1, Point p2, Pen pen)
{
using (var graphics = Graphics.FromImage(bmp))
{
graphics.DrawLine(pen, p1.X, p1.Y, p2.X, p2.Y);
}
}
private static List<Point> DrawRaster(int edge, Bitmap image, GraphicsPath path)
{
var points = new List<Point>();
var countHorizontal = image.Width / edge;
var countVertical = image.Height / edge;
using (var graphics = Graphics.FromImage(image))
{
for (int x = 0; x < countHorizontal; x++)
{
for (int y = 0; y < countVertical; y++)
{
var boxX = (x * edge) + (edge / 2);
var boxY = (y * edge) + (edge / 2);
if (!path.IsVisible(boxX, boxY))
{
continue;
}
points.Add(new Point(boxX, boxY));
graphics.DrawRectangle(Pens.LightGray, x * edge, y * edge, edge, edge);
}
}
}
return points;
}
}
}

Related

How do I rotate an Image and Scale it up using only one method?

Here's what I do to Rotate and Scale. But so far, if the rotation is working, the scaling isn't and vice versa. So how do I combine rotation and scaling in one method? I feels like they can't coexist using my code.
....................................................................................................................................................................
Here's what I have for now:
Image Drawing:
public LayerClass ImageDrawing(LayerClass.Type img, Bitmap bm, Rectangle imgRect, String filepath, int angle, PaintEventArgs e)
{
bm = ImageClass.GrayscaleImage(bm);
bm = MakeTransparentImage(bm);
e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
bm = RotateImage(bm, angle, imgRect);
imgRect = new Rectangle((int)(Shape.center.X - (bm.Width / 2)), (int)(Shape.center.Y - (bm.Height / 2)), (int)bm.Width, (int)bm.Height);
e.Graphics.DrawImage(bm, imgRect);
this.imageBitmap = bm;
this.filePath = filePath;
this.rotationAngle = angle;
this.location = location;
this.imageRect = imgRect;
return new LayerClass(LayerClass.Type.Image, this, filePath, imgRect);
}
Rotation:
public static Bitmap RotateImage(Bitmap bitmap, float angle, Rectangle rect)
{
Matrix matrix = new Matrix();
matrix.Translate(bitmap.Width / -2, bitmap.Height / -2, MatrixOrder.Append);
matrix.RotateAt(angle, new System.Drawing.Point(0, 0), MatrixOrder.Append);
using (GraphicsPath graphicsPath = new GraphicsPath())
{
graphicsPath.AddPolygon(new System.Drawing.Point[] { new System.Drawing.Point(0, 0), new System.Drawing.Point(bitmap.Width, 0), new System.Drawing.Point(0, bitmap.Height) });
graphicsPath.Transform(matrix);
System.Drawing.PointF[] points = graphicsPath.PathPoints;
rect = boundingBox(bitmap, matrix);
Bitmap resultBitmap = new Bitmap(rect.Width, rect.Height);
using (Graphics g = Graphics.FromImage(resultBitmap))
{
Matrix matrix2 = new Matrix();
matrix2.Translate(resultBitmap.Width / 2, resultBitmap.Height / 2, MatrixOrder.Append);
g.Transform = matrix2;
g.DrawImage(bitmap, points);
return resultBitmap;
}
}
}
Scaling:
private void trackBar_ScaleImg_Scroll(object sender, EventArgs e)
{
if(rb_BothImage.Checked)
{
if (imgRect.Width > imgRect.Height)
{
imgRect.Width = trackBar_ScaleImg.Value;
imgRect.Height = (int)(trackBar_ScaleImg.Value / aspect);
ImageBitmap = new Bitmap(ImageBitmap, new Size(imgRect.Width, imgRect.Height));
}
else if (imgRect.Height > imgRect.Width)
{
imgRect.Height = trackBar_ScaleImg.Value; //64mm
imgRect.Width = (int)(trackBar_ScaleImg.Value / aspect);
ImageBitmap = new Bitmap(ImageBitmap, new Size(imgRect.Width, imgRect.Height));
}
else if (imgRect.Width == imgRect.Height)
{
imgRect.Width = trackBar_ScaleImg.Value;
imgRect.Height = trackBar_ScaleImg.Value;
}
imgRect.X = (int)(Shape.center.X - (imgRect.Width / 2));
imgRect.Y = (int)(Shape.center.Y - (imgRect.Height / 2));
ImageBitmap = new Bitmap(ImageBitmap, new Size(imgRect.Width, imgRect.Height));
}
pictureBox_Canvass.Invalidate();
}
You can add another matrix transformation for scaling: matrix.Scale(2, 2, MatrixOrder.Append);
Matrix matrix = new Matrix();
matrix.Translate(bitmap.Width / -2, bitmap.Height / -2, MatrixOrder.Append);
matrix.RotateAt(angle, new System.Drawing.Point(0, 0), MatrixOrder.Append);
matrix.Scale(2, 2, MatrixOrder.Append);
using (GraphicsPath graphicsPath = new GraphicsPath())

Is there any way to draw 2D shapes in Viewport3D like arc, line, point and plane?

Right now I am using Viewport3D in which I am drawing all 3D shapes but I also want to draw arc, point and lines in Viewport3D. Can anyone help me with this?
private Viewport2DVisual3D ArcModel;
private Model3DGroup group;
MeshGeometry3D testGeometry = new MeshGeometry3D();
PathFigure pthFigure = new PathFigure();
pthFigure.StartPoint = new Point(1, 1);
ArcSegment arcSeg = new ArcSegment();
arcSeg.Point = new Point(30, 30);
arcSeg.Size = new Size(20, 20);
arcSeg.IsLargeArc = true;
arcSeg.SweepDirection = SweepDirection.Counterclockwise;
//arcSeg.RotationAngle = 30;
PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();
myPathSegmentCollection.Add(arcSeg);
pthFigure.Segments = myPathSegmentCollection;
PathFigureCollection pthFigureCollection = new PathFigureCollection();
pthFigureCollection.Add(pthFigure);
PathGeometry pthGeometry = new PathGeometry();
pthGeometry.Figures = pthFigureCollection;
Path arcPath = new Path();
arcPath.Stroke = new SolidColorBrush(Colors.Violet);
arcPath.StrokeThickness = 1;
arcPath.Data = pthGeometry;
//arcPath.Fill = new SolidColorBrush(Colors.Yellow);
//Children.Add(arcPath);
Point3DCollection myPoint3DCollection = new Point3DCollection();
myPoint3DCollection.Add(new Point3D(0, 0, 0));
myPoint3DCollection.Add(new Point3D(0, 0, 2));
myPoint3DCollection.Add(new Point3D(0, 2, 0));
myPoint3DCollection.Add(new Point3D(0, 2, 2));
testGeometry.Positions = myPoint3DCollection;
PointCollection myPointCollection = new PointCollection();
myPointCollection.Add(new Point(0, 1));
myPointCollection.Add(new Point(1, 1));
myPointCollection.Add(new Point(0, 0));
myPointCollection.Add(new Point(1, 0));
testGeometry.TextureCoordinates = myPointCollection;
Int32Collection triangleIndicesCollection = new Int32Collection();
triangleIndicesCollection.Add(0);
triangleIndicesCollection.Add(1);
triangleIndicesCollection.Add(2);
triangleIndicesCollection.Add(2);
triangleIndicesCollection.Add(1);
triangleIndicesCollection.Add(3);
testGeometry.TriangleIndices = triangleIndicesCollection;
DiffuseMaterial myDiffuseMaterial = new DiffuseMaterial(Brushes.White);
Viewport2DVisual3D.SetIsVisualHostMaterial(myDiffuseMaterial, true);
ArcModel = new Viewport2DVisual3D();
ArcModel.Material = myDiffuseMaterial;
ArcModel.Geometry = testGeometry;
//group.Children.Add(ArcModel.Geometry);
ArcModel.Visual = arcPath;
ArcGeomodel = new GeometryModel3D(ArcModel.Geometry, myDiffuseMaterial);
ArcGeomodel.Transform = new Transform3DGroup();
group.Children.Add(ArcGeomodel);
viewport.Children.Add(ArcModel);
I am drawing this arc using path geometry and adding it into Viewport2DVisual3D but its not getting displayed...
what I am missing here ...please suggest any solution
Finally got what I was missing.I was missing to add transformation and rotation to it
following is the code
Transform3DGroup myTransform3DGroup = new Transform3DGroup();
RotateTransform3D rotateTransform = new RotateTransform3D()
{
Rotation = new AxisAngleRotation3D
{
Angle = 40,
Axis = new Vector3D(0, 1, 0)
}
};
myTransform3DGroup.Children.Add(rotateTransform);
ArcModel.Transform = myTransform3DGroup;
ArcModel.Material = myDiffuseMaterial;
ArcModel.Geometry = testGeometry;
ArcModel.Visual = arcPath;
viewport.Children.Add(ArcModel);
Hope this will help someone!

Blob doesn`t match tracking object

hi,
I need to use color tracking.
The blob does not match my target object when I run my code in surface pro 4.
but the code is correct when I test it on my Acer.
anyone knows that why?
public void forobject(Bitmap image)//put setted color value into image1
{
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/2, image.Height/2), 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();
pictureBox_tracking.Image = image;//????
if (rdiobtn_singletracking.Checked)
{
// Single Tracking--------
foreach (Rectangle recs in rects)
{
if (rects.Length > 0)
{
Rectangle objectRect = rects[0];
//Graphics g = Graphics.FromImage(image);
Graphics g = pictureBox_real.CreateGraphics();
using (Pen pen = new Pen(Color.FromArgb(252, 3, 26), 2))
{
g.DrawRectangle(pen, objectRect);
}
//Drawn by the rectangle coordinates is taken away.
//int objectX = objectRect.X; //+ (objectRect.Width / 2);
//int objectY = objectRect.Y; //+ (objectRect.Height / 2);
x = objectRect.X;
y = objectRect.Y;
w = objectRect.Width;
h = objectRect.Height;
// g.DrawString(objectX.ToString() + "X" + objectY.ToString(), new Font("Arial", 12), Brushes.Red, new System.Drawing.Point(250, 1));
g.Dispose();
}

Drawing polygon with more than one hole?

I'm trying to draw a polygon with more than one holes. I tried the following code and it does not work correctly. Please advise.
PointF[] mypoly = new PointF[6 + 5 + 5];
mypoly[0] = new PointF(0, 0);
mypoly[1] = new PointF(100, 0);
mypoly[2] = new PointF(100, 100);
mypoly[3] = new PointF(0, 100);
mypoly[4] = new PointF(10, 80);
mypoly[5] = new PointF(0, 0);
mypoly[6] = new PointF(10, 10);
mypoly[7] = new PointF(10, 20);
mypoly[8] = new PointF(20, 20);
mypoly[9] = new PointF(20, 10);
mypoly[10] = new PointF(10, 10);
mypoly[11] = new PointF(40, 10);
mypoly[12] = new PointF(40, 20);
mypoly[13] = new PointF(60, 20);
mypoly[14] = new PointF(60, 10);
mypoly[15] = new PointF(40, 10);
g.FillPolygon(new SolidBrush(Color.Red), mypoly, FillMode.Winding);
The first part is the outer polygon. The second and the third parts are the two holes inside the polygon.
Use a GraphicsPath instead. You can draw it with Graphics.FillPath, like this:
using System.Drawing.Drawing2D;
...
using (var gp = new GraphicsPath()) {
PointF[] outer = new PointF[] { new PointF(0, 0), new PointF(100, 0),
new PointF(100, 100), new PointF(0, 100), new PointF(10, 80),new PointF(0, 0) };
gp.AddPolygon(outer);
PointF[] inner1 = new PointF[] { new PointF(10, 10), new PointF(10, 20),
new PointF(20, 20), new PointF(20, 10), new PointF(10, 10) };
gp.AddPolygon(inner1);
PointF[] inner2 = new PointF[] { new PointF(40, 10), new PointF(40, 20),
new PointF(60, 20), new PointF(60, 10), new PointF(40, 10) };
gp.AddPolygon(inner2);
e.Graphics.FillPath(Brushes.Black, gp);
}

How do I draw an annulus (doughnut) using GDI+?

I have been trying to draw an annulus (ring with thickness) with a transparent hole and a gradient rim in C# with very little success. Does anyone have any suggestions on how to do this?
here's a nice Blend Utility
Here's the Final result - thanks to BlueMonkMN
Rectangle GetSquareRec(double radius, int x, int y)
{
double r = radius;
double side = Math.Sqrt(Math.Pow(r, 2) / 2);
Rectangle rec = new Rectangle(x - ((int)side), y - ((int)side), (int)(side * 2) + x, (int)(side * 2) + y);
return rec;
}
void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics gTarget = e.Graphics;
gTarget.SmoothingMode = SmoothingMode.AntiAlias;
GraphicsPath pTemp = new GraphicsPath();
Rectangle r = GetSquareRec(200, 225, 225);
pTemp.AddEllipse(r);
pTemp.AddEllipse(GetSquareRec(50, 225, 225));
Color[] colors = new Color[5];
colors[0] = Color.FromArgb(192, 192, 192);
colors[1] = Color.FromArgb(105, 0, 0);
colors[2] = Color.FromArgb(169, 169, 169);
colors[3] = Color.FromArgb(0, 0, 0);
colors[4] = Color.FromArgb(0, 0, 0);
float[] positions = new float[5];
positions[0] = 0f;
positions[1] = 0.1f;
positions[2] = 0.35f;
positions[3] = 0.5f;
positions[4] = 1f;
ColorBlend Cb = new ColorBlend();
Cb.Colors = colors;
Cb.Positions = positions;
PathGradientBrush pgb = new PathGradientBrush(pTemp);
pgb.InterpolationColors = Cb;
pgb.CenterPoint = new PointF(r.X + (r.Width / 2), r.Y + (r.Height / 2));
gTarget.FillPath(pgb, pTemp);
}
http://www.freeimagehosting.net/uploads/th.515733e62e.jpg
This is how I did it in the Scrolling Game Development Kit:
pTemp = new GraphicsPath();
pTemp.AddEllipse(Start.X, Start.Y, End.X - Start.X, End.Y - Start.Y);
pTemp.AddEllipse((Start.X * 3 + End.X) / 4f,
(Start.Y * 3 + End.Y) / 4f,
(End.X - Start.X) / 2f,
(End.Y - Start.Y) / 2f);
PathGradientBrush pgb = new PathGradientBrush(pTemp);
Blend b = new Blend();
b.Factors = new float[] { 0, 1, 1 };
b.Positions = new float[] { 0, .5F, 1 };
pgb.Blend = b;
pgb.CenterColor = ((SolidBrush)CurrentBrush).Color;
pgb.SurroundColors = new Color[] {CurrentPen.Color};
gTarget.FillPath(pgb, pTemp);
pgb.Dispose();
pTemp.Dispose();
(source: enigmadream.com)
I edited the original SGDK code for this sample because originally I wasn't smart enough to scale the gradient to exclude the hole, but now I guess I am :).
If you would rather see the gradient like this:
(source: enigmadream.com)
Then change the blend code to look like this:
Blend blend = new Blend();
blend.Factors = new float[] { 0, 1, 0, 0 };
blend.Positions = new float[] { 0, 0.25F, .5F, 1 };
pgb.Blend = blend;
You may use two calls to Graphics.DrawArc combined, drawing the top and bottom or left and right portions of the annulus, one portion at a time.

Categories