Wednesday, March 6, 2019

c# - Calculate random points (pixel) within a circle (image)


I have an image that contains a circles at a specific location, and of a specific diameter. What I need to do is to be able to calculate random points within the circle, and then manipulate the pixels said points correlate to. I have the following code already:



private Point CalculatePoint()
{
var angle = _random.NextDouble() * ( Math.PI * 2 );
var x = _originX + ( _radius * Math.Cos( angle ) );
var y = _originY + ( _radius * Math.Sin( angle ) );
return new Point( ( int )x, ( int )y );
}

And that works fine for finding all the points at the circumference of the circle, but I need all points from anywhere in the circle. If this doesn't make sense let me know and I will do my best to clarify.



Answer




If you want a simple solution just randomize the radius too:


private Point CalculatePoint()
{
var angle = _random.NextDouble() * Math.PI * 2;
var radius = _random.NextDouble() * _radius;
var x = _originX + radius * Math.Cos(angle);
var y = _originY + radius * Math.Sin(angle);
return new Point((int)x,(int)y);
}


That however results in your points being more concentrated towards the center of the circle:


enter image description here


In order to get an uniform distribution make the following change to the algorithm:


var radius = Math.Sqrt(_random.NextDouble()) * _radius;

Which will give the following result:


enter image description here


For more information check the following link: MathWorld - Disk Point Picking.


And finally here's a simple JsFiddle demonstration comparing both version of the algorithm.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...