I am having trouble with Bresenham's algorithm - c#

It only works when slope is between 0 and 1. i'm not sure where to go from here. thanks for your help! This method reads in two points and draws the line between them using bresenhams algo. I don't know where to go to optimize it for all lines. thanks for your help.
void Bresenhams(int x1, int y1, int xk, int yk)
{
int deltaX = xk - x1;
int deltaY = yk - y1;
int error = 0;
int y = y1;
int x = x1;
int doubleDeltaX = 2 * deltaX;
bool steep = Math.Abs(yk - y1) > Math.Abs(xk - x1);
canvas.SetPixel(x1, y1, Color.Black);
if (!steep)
{
for (int i = x1 + 1; i <= xk; i++)
{
if (x1 > xk)
{
int temp = x1;
x1 = xk;
xk = temp;
temp = y1;
y1 = yk;
yk = temp;
}
error = error + deltaY;
if (error > deltaX)
{
y++;
error -= doubleDeltaX;
}
canvas.SetPixel(i, y, Color.Black);
}
}
else
{
for (int i = y1 + 1; i <= yk; i++)
{
if (y1 > yk)
{
int temp = x1;
x1 = xk;
xk = temp;
temp = y1;
y1 = yk;
yk = temp;
}
error = error + deltaY;
if (error > deltaY)
{
y++;
error -= doubleDeltaX;
}
canvas.SetPixel(x, i, Color.Black);
}
}
pictureBox1.Image = canvas;
}

Divide a circle into 8 parts. You can run Bresenham over one octant and draw all 8 at the same time. For center at 0,0:
0-45 x,y
45-90 y,x
90-135 -y,x
135-180 -x,y
180-225 -x,-y
225-270 -y,-x
270-315 y,-x
315-360 x,-y

Related

Ambiguous cases in Marching square algorithm

If we take Wikipedia article on Marching square into account, we see that case#5 and case#10 are said to be ambiguous cases.
I have implemented Marching Square as follows and I am not understanding how an ambiguous case can arise:
public class LinesRectangle
{
public Graphics Graphics { get; set; }
public Color Color { get; set; }
public Pen Pen { get; set; }
public int Thickness { get; set; }
public LinesRectangle()
{
Color = Color.Blue;
Thickness = 2;
Pen = new Pen(Color, Thickness);
}
public void DrawLines(int x, int y, int width, int code)
{
int height = width;
Graphics.DrawRectangle(Pen, new System.Drawing.Rectangle(x, y, width, height));
int x1 = 0, y1 = 0;
int x2 = 0, y2 = 0;
switch (code)
{
case 0:
case 15:
break;
case 1:
case 14:
x1 = x; y1 = y + height/2;
x2 = x + width/2; y2 = y + height;
Graphics.DrawLine(Pen, x1, y1, x2, y2);
break;
case 2:
case 13:
x1 = x + width/2; y1 = y + height;
x2 = x + width; y2 = y + height/2;
Graphics.DrawLine(Pen, x1, y1, x2, y2);
break;
case 3:
case 12:
x1 = x; y1 = y + height / 2;
x2 = x + width; y2 = y + height / 2;
Graphics.DrawLine(Pen, x1, y1, x2, y2);
break;
case 4:
case 11:
x1 = x+width/2; y1 = y;
x2 = x + width; y2 = y + height / 2;
Graphics.DrawLine(Pen, x1, y1, x2, y2);
break;
case 5:
x1 = x ; y1 = y + height/2;
x2 = x + width/2; y2 = y;
Graphics.DrawLine(Pen, x1, y1, x2, y2);
x1 = x + width / 2; y1 = y + height;
x2 = x + width; y2 = y + height / 2;
Graphics.DrawLine(Pen, x1, y1, x2, y2);
break;
case 6:
case 9:
x1 = x + width / 2; y1 = y;
x2 = x + width/2; y2 = y + height;
Graphics.DrawLine(Pen, x1, y1, x2, y2);
break;
case 7:
case 8:
x1 = x; y1 = y + height / 2;
x2 = x + width / 2; y2 = y;
Graphics.DrawLine(Pen, x1, y1, x2, y2);
break;
case 10:
x1 = x + width / 2; y1 = y;
x2 = x + width; y2 = y + height / 2;
Graphics.DrawLine(Pen, x1, y1, x2, y2);
x1 = x; y1 = y + height / 2;
x2 = x + width / 2; y2 = y + height;
Graphics.DrawLine(Pen, x1, y1, x2, y2);
break;
}
}
}
You can see here each of the cases are taken care of individually.
Output:
Can anyone tell me what I am missing?
Driver Program:
public enum What
{
lines, surface, both
}
public partial class DrawingForm : System.Windows.Forms.Form
{
public int [,] Data { get; set; }
public void Print(int[,] data, int xn, int yn)
{
for (int j = 0; j < yn; j++)
{
for (int i = 0; i < xn; i++)
{
Console.Write(data[i, j] + ", ");
}
Console.WriteLine();
}
}
public int[,] normalize(int[,] data, int xn, int yn)
{
for (int j = 0; j < yn; j++)
{
for (int i = 0; i < xn; i++)
{
if (data[i, j] > 1)
{
data[i, j] = 0;
}
else
{
data[i, j] = 1;
}
}
}
return data;
}
public int[,] marching_square(int x, int y, int[,] data, int isovalue, What what)
{
int xn = x;
int yn = y;
data = normalize(data, xn, yn);
int[,] bitMask = new int[xn - 1, yn - 1];
for (int j = 0; j < yn - 1; j++)
{
for (int i = 0; i < xn - 1; i++)
{
StringBuilder sb = new StringBuilder();
sb.Append(data[i, j]);
sb.Append(data[i + 1, j]);
sb.Append(data[i + 1, j + 1]);
sb.Append(data[i, j + 1]);
bitMask[i, j] = Convert.ToInt32(sb.ToString(), 2);
}
}
return bitMask;
}
public DrawingForm()
{
InitializeComponent();
}
private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
int[,] data = new int[,] {
{ 1,1,1,1,1 },
{ 1,2,3,2,1 },
{ 1,3,1,3,1 },
{ 1,2,3,2,1 },
{ 1,1,1,1,1 }
};
int[,] bitMask = marching_square(5, 5, data, 0, What.lines);
Graphics g = this.CreateGraphics();
LinesRectangle rect = new LinesRectangle();
rect.Graphics = g;
for (int j = 0; j < 4; j++)
{
for (int i = 0; i < 4; i++)
{
rect.DrawLines(i*50, j*50, 50, bitMask[i,j]);
}
}
}
}
Edit: In case of the following data (as pointed out by #JeremyLakeman):
{ 2,1,2,1,2 },
{ 1,2,1,2,1 },
{ 2,1,2,1,2 },
{ 1,2,1,2,1 },
{ 2,1,2,1,2 }
my program produced the following output:
Your example doesn't include any ambiguous cases. What output would you expect with the following input;
{ 2,1,2,1,2 },
{ 1,2,1,2,1 },
{ 2,1,2,1,2 },
{ 1,2,1,2,1 },
{ 2,1,2,1,2 }
Circles around the 1's? Circles around the 2's? Diagonal lines?
Edit;
From your code;
case 5:
x1 = x ; y1 = y + height/2;
x2 = x + width/2; y2 = y;
Graphics.DrawLine(Pen, x1, y1, x2, y2);
x1 = x + width / 2; y1 = y + height;
x2 = x + width; y2 = y + height / 2;
Graphics.DrawLine(Pen, x1, y1, x2, y2);
break;
case 10:
x1 = x + width / 2; y1 = y;
x2 = x + width; y2 = y + height / 2;
Graphics.DrawLine(Pen, x1, y1, x2, y2);
x1 = x; y1 = y + height / 2;
x2 = x + width / 2; y2 = y + height;
Graphics.DrawLine(Pen, x1, y1, x2, y2);
break;
You could swap those case labels. You could pick one, delete the other, and merge the cases. You could look at more surrounding pixels to pick one. You could roll a random number to pick which way to draw it.
But you didn't. You arbitrarily decided that you would always draw those cases this way.
Oh man, I understand you. Surprisingly thats a good question!
Ambiguity is seen clearly in a moment when you decide if "value above the isovalue" is black or white and opposite for the "value below the isovalue".
Let me explain what I mean.
If you do algorithm by hand you can get following results. The only choice you do while following algorithm described on wiki - is to decide what color to use when painting nodes.
{ 1, 1, 1 },
{ 1, 2, 1 },
{ 1, 1, 1 }
has no ambiguous cases so the choice does not matter - resulting image will be the same no matter if '1' is a "black dot" or a "white dot".
BUT lets see example with ambiguous cases:
{ 1, 2, 1 },
{ 2, 1, 2 },
{ 1, 2, 1 }
algorith would provide a circle around the middle point if '1's are white, and same algorithm would provide 4 arcs near the middle points if '1's are chosen to be black.
I think moment of choice is in normalize function at
if (data[i, j] > 1)
If you change ">" to "<" you will get change of image for ambigous cases. And it would change nothing for non-ambigous cases. Ambiguity is easier to understand if you look at methods idea not algorithm. Look at saddle point - there is ambiguity in drawing contour because from the one hand saddle point is a minimum and from the other its a maximum - depends on direction of measurements.
Hope that helps to clear the confusion.
Edit: I elaborated in comments but for visibility I'm duplicating it here

SystemArgumentOutOfRangeException C#

namespace Cropping_Image
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var img = new Bitmap(Image.FromFile(#"C:\Users\Overnighter\Desktop\test.png"));
int num = 1;
int x1 = 0;
var x2 = 120;
int y1 = 0;
var y2 = 120;
while (x2 != img.Width)
{
var width = x2 - x1+1;
var height = y2 - y1+1;
var result = new Bitmap(width, height);
for (var i = x1; i <= x2; i++)
for (var j = y1; j <= y2; j++)
result.SetPixel(i - x1, j - y2, img.GetPixel(i, j));
result.Save(#"C:\Users\Overnighter\Desktop\file\"+ num +".png");
num++;
x1 += 120;
x2 += 120;
}
}
}
}
Specification of the Error:
System.ArgumentOutOfRangeException: "The parameter must be positive and less than the height.
Parameter name: y "
How can I fix this error?
In that Piece of code:
result.SetPixel(**i - x1**, **j - y2**, img.GetPixel(i, j));
You need to be sure that i - x1 (x parameter) and j - y2 (y parameter) are positive,
i think that something like that should be enought to remove the exception:
for (var i = x1; i <= x2; i++)
for (var j = y1; j <= y2; j++)
if((i - x1)>=0 && (j - y2)>=0)
result.SetPixel(i - x1, j - y2, img.GetPixel(i, j));
but if you get that message you're probably soing something wrong u.u

calculate the Euclidean distance between an array in c# with function

I want to calculate a euclidean distance between points that the user enter,so as you can see here :
static void Main(string[] args)
{
int numtest = int.Parse(Console.ReadLine());
int[,] points=new int[10,2];
for (int i = 0; i < numtest; i++)
{
Console.WriteLine("point " +(i+1).ToString()+" x: ");
points[i, 0] = int.Parse(Console.ReadLine());
Console.WriteLine("point " + (i + 1).ToString() + " y: ");
points[i, 1] = int.Parse(Console.ReadLine());
}
}
public float[] calculate(int[,] points)
{
for (int i = 0; i <points.Length ; i++)
{
}
}
is there any function in c# that can do this ?
I need to have each distance value between all points in my array
Here is how to implement the distance calculation between two given points, to get you started:
int x0 = 0;
int y0 = 0;
int x1 = 100;
int y1 = 100;
int dX = x1 - x0;
int dY = y1 - y0;
double distance = Math.Sqrt(dX * dX + dY * dY);
Try following
public void calculate(double[,] points)
{
var distanceArray = new double[points.Length, points.Length];
for (int i = 0; i < points.Length; i++)
for (int j = 0; j < points.Length; j++)
distanceArray[i, j] = Distance(points[i, 0], points[i, 1], points[j, 0], points[j, 1]);
}
public static double Distance(double x1, double y1, double x2, double y2)
=> Math.Sqrt(((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)));

Get all points within a Triangle

I have three points, for example:
Start 194 171
Right 216 131
Left 216 203
I want to get all the points within that triangle. How would I do that efficiently?
see z3nth10n's answer for better input validation
Introduction:
The general idea was to get the triangle's edges (y-Wise) for every x in it's range, and then you have all the y's that exist within the triangle for every single x, which with simple conversion turns into all points within the triangle.
You can look at it as if you cut the triangle into stripes, each being of width 1.
So for X=0, on the line between A and B, the Y is 6, and on the line between A and C, the Y is -2, so you can see that the stripe of X=0 is between -2 and 6. Therefore, you can tell that (0, -2) (0, -1) (0, 0) ... (0, 5) (0, 6) are all in the triangle. Doing that for X's between the smallest and the largest within the triangle, and you have all the points in the triangle!
Speed:
For the triangle (0, 0) (1, 8) (4, 6) - found 16 points.
Done 1,000,000 times in 3.68 seconds.
Implementation:
public IEnumerable<Point> PointsInTriangle(Point pt1, Point pt2, Point pt3)
{
if (pt1.Y == pt2.Y && pt1.Y == pt3.Y)
{
throw new ArgumentException("The given points must form a triangle.");
}
Point tmp;
if (pt2.X < pt1.X)
{
tmp = pt1;
pt1 = pt2;
pt2 = tmp;
}
if (pt3.X < pt2.X)
{
tmp = pt2;
pt2 = pt3;
pt3 = tmp;
if (pt2.X < pt1.X)
{
tmp = pt1;
pt1 = pt2;
pt2 = tmp;
}
}
var baseFunc = CreateFunc(pt1, pt3);
var line1Func = pt1.X == pt2.X ? (x => pt2.Y) : CreateFunc(pt1, pt2);
for (var x = pt1.X; x < pt2.X; x++)
{
int maxY;
int minY = GetRange(line1Func(x), baseFunc(x), out maxY);
for (var y = minY; y <= maxY; y++)
{
yield return new Point(x, y);
}
}
var line2Func = pt2.X == pt3.X ? (x => pt2.Y) : CreateFunc(pt2, pt3);
for (var x = pt2.X; x <= pt3.X; x++)
{
int maxY;
int minY = GetRange(line2Func(x), baseFunc(x), out maxY);
for (var y = minY; y <= maxY; y++)
{
yield return new Point(x, y);
}
}
}
private int GetRange(double y1, double y2, out int maxY)
{
if (y1 < y2)
{
maxY = (int)Math.Floor(y2);
return (int)Math.Ceiling(y1);
}
maxY = (int)Math.Floor(y1);
return (int)Math.Ceiling(y2);
}
private Func<int, double> CreateFunc(Point pt1, Point pt2)
{
var y0 = pt1.Y;
if (y0 == pt2.Y)
{
return x => y0;
}
var m = (double)(pt2.Y - y0) / (pt2.X - pt1.X);
return x => m * (x - pt1.X) + y0;
}
#SimpleVar answer is well, but it lacks a good check for valid triangles. (This can cause an overflow problem).
So I do my own implementation for Unity3D:
public static IEnumerable<T> PointsInTriangle<T>(T pt1, T pt2, T pt3)
where T : IPoint
{
/*
// https://www.geeksforgeeks.org/check-whether-triangle-valid-not-sides-given/
a + b > c
a + c > b
b + c > a
*/
float a = Vector2.Distance(new Vector2(pt1.x, pt1.y), new Vector2(pt2.x, pt2.y)),
b = Vector2.Distance(new Vector2(pt2.x, pt2.y), new Vector2(pt3.x, pt3.y)),
c = Vector2.Distance(new Vector2(pt3.x, pt3.y), new Vector2(pt1.x, pt1.y));
if (a + b <= c || a + c <= b || b + c <= a)
{
Debug.LogWarning($"The given points must form a triangle. {{{pt1}, {pt2}, {pt3}}}");
yield break;
}
if (TriangleArea(pt1, pt2, pt3) <= 1)
{
Point center = GetTriangleCenter(pt1, pt2, pt3);
yield return (T)Activator.CreateInstance(typeof(T), center.x, center.y);
return;
}
T tmp;
if (pt2.x < pt1.x)
{
tmp = pt1;
pt1 = pt2;
pt2 = tmp;
}
if (pt3.x < pt2.x)
{
tmp = pt2;
pt2 = pt3;
pt3 = tmp;
if (pt2.x < pt1.x)
{
tmp = pt1;
pt1 = pt2;
pt2 = tmp;
}
}
var baseFunc = CreateFunc(pt1, pt3);
var line1Func = pt1.x == pt2.x ? (x => pt2.y) : CreateFunc(pt1, pt2);
for (var x = pt1.x; x < pt2.x; ++x)
{
int maxY;
int minY = GetRange(line1Func(x), baseFunc(x), out maxY);
for (int y = minY; y <= maxY; ++y)
yield return (T)Activator.CreateInstance(typeof(T), x, y);
}
var line2Func = pt2.x == pt3.x ? (x => pt2.y) : CreateFunc(pt2, pt3);
for (var x = pt2.x; x <= pt3.x; ++x)
{
int maxY;
int minY = GetRange(line2Func(x), baseFunc(x), out maxY);
for (int y = minY; y <= maxY; ++y)
yield return (T)Activator.CreateInstance(typeof(T), x, y);
}
}
private static int GetRange(float y1, float y2, out int maxY)
{
if (y1 < y2)
{
maxY = Mathf.FloorToInt(y2);
return Mathf.CeilToInt(y1);
}
maxY = Mathf.FloorToInt(y1);
return Mathf.CeilToInt(y2);
}
private static Func<int, float> CreateFunc<T>(T pt1, T pt2)
where T : IPoint
{
var y0 = pt1.y;
if (y0 == pt2.y)
return x => y0;
float m = (float)(pt2.y - y0) / (pt2.x - pt1.x);
return x => m * (x - pt1.x) + y0;
}
public static float TriangleArea<T>(T p1, T p2, T p3)
where T : IPoint
{
float a, b, c;
if (!CheckIfValidTriangle(p1, p2, p3, out a, out b, out c))
return 0;
return TriangleArea(a, b, c);
}
public static float TriangleArea(float a, float b, float c)
{
// Thanks to: http://james-ramsden.com/area-of-a-triangle-in-3d-c-code/
float s = (a + b + c) / 2.0f;
return Mathf.Sqrt(s * (s - a) * (s - b) * (s - c));
}
public static Point GetTriangleCenter<T>(T p0, T p1, T p2)
where T : IPoint
{
// Thanks to: https://stackoverflow.com/questions/524755/finding-center-of-2d-triangle
return new Point(p0.x + p1.x + p2.x / 3, p0.y + p1.y + p2.y / 3);
}
public static bool CheckIfValidTriangle<T>(T v1, T v2, T v3, out float a, out float b, out float c)
where T : IPoint
{
a = Vector2.Distance(new Vector2(v1.x, v1.y), new Vector2(v2.x, v2.y));
b = Vector2.Distance(new Vector2(v2.x, v2.y), new Vector2(v3.x, v3.y));
c = Vector2.Distance(new Vector2(v3.x, v3.y), new Vector2(v1.x, v1.y));
if (a + b <= c || a + c <= b || b + c <= a)
return false;
return true;
}
IPoint interface could be a good point for own Point implementations (for libs like Clipper, TessDotNet or Poly2Tri). You can change it at any time (two UnityEngine.Vector2 or System.Drawing.Point).
Hope this helps!
EDIT: I solved all bugs here:
Also I answered my own question asking this: https://stackoverflow.com/a/53734816/3286975

How to write bresenham algorithms in c#?

I wrote like this but it works only in 50% cases. Can someone tell what's wrong?
public void Bresenham(int x1,int y1,int x2,int y2,Color c)
{
double dx = x2 - x1;
double dy = y2 - y1;
double d = 2*dy-dx; //aux variable
double p1 = 2 * dy ;
double p2 = 2 * (dy - dx);
int x = x1;
int y = y1;
int xend;
c = kolor;
if (x1 > x2)
{
x = x2;
y = y2;
xend = x1;
}
else
{
x = x1;
y = y1;
xend = x2;
}
bitmapa.SetPixel(x, y,c);
try
{
while (x < xend)
{
x++;
if (d < 0)
{
d += p1;
}
else
{
d += p2;
y += 1;
}
bitmapa.SetPixel(x, y, c);
}
}
Thanks:)
At first shot, you are missing a case when other coordinate should be handled like now your are handling Y. You now handle the case when DY < DX, you should also handle case when DX < DY, i.e. slope of the line is different.
To understand what I'm saying, look steep here.
And actually, your algorithm will work only in 1/4 cases.

Categories

Resources