2567655222
2567655222

Reputation: 167

Determine if points are within ellipse (Python and Pillow)

Using PIL, I've drawn an ellipse using the square coordinates around the circle (ie, the X and Y coordinates of the shape if it were a square).

I want to determine if coordinates I pass in are within the range of the coordinates of the ellipse. If this were a square, I imagine this would be relatively easy, as I could simply ask the script to determine if the coordinates (x and y) are between the range of x and y coordinates of the square.

However, because it's an ellipse, I do not know the coordinates of the lines produced by the arc. For this reason, I believe I need a PIL solution to give me the range of the ellipse line first. Does this exist natively in PIL?

Upvotes: 0

Views: 246

Answers (1)

Don Fruendo
Don Fruendo

Reputation: 350

Full handwork solution incoming

Since an ellipse is just a "stuffed circle", one could resize the ellipse to be a circle and move on from there.

You have the coordinates, so the first step is to resize.

x_diff = abs(x_max - x_min)
x = (x - x_min ) / x_diff
y_diff = abs(y_max - y_min)
y = (y - y_min ) / y_diff

This resizes the ellipse to a circle with radius .5.

Using Pythagora's theorem, the distance to (0, 0) should be lower than the distances to the x and y axis, each squared. So a² + b² = c² becomes c <= sqrt(a² + b²). And since we have scaled the ellipse to a circle with radius 0.5, we can assume, that c has to be smaller or equal to 0.5.

import math

c = math.sqrt(x**2 + y**2)
if c <= .5:
    print("Coordinate lies within ellipse!")
else:
   print("Try again :(")

Upvotes: 1

Related Questions