Q2Learn
Q2Learn

Reputation: 323

How to check if a point is in an ellipse in python

How do I find a point within an angled ellipse in python? I wrote out the equation in a function and I am drawing a black picture with the ellipse in white and the point in blue. I am then calculating if the point is within the ellipse which it is showing up in the picture but the function is returning as false. What am I missing?

Thanks!

# Create a black image for ellipse ROI
img = np.zeros((240, 320, 3), np.uint8)

# ellipse
ellipse_center_x = 160
ellipse_center_y = 120
ellipse_axis_x = 100
ellipse_axis_y = 20
ellipse_angle = -40
start_angle = 0
end_angle = 360

# detection point example
xCenter = 135
yCenter = 135

def pointInEllipse(img, xp, yp, x, y, axis_x, axis_y, angle):
    
    # # WITH StackOverflow Answer Edits
    angle_rad = math.radians(angle)
    cosa = math.cos(angle_rad)
    sina = math.sin(angle_rad)

    # # Equation of point within angled ellipse
    a = (((cosa * (xp - x) + sina * (yp - y)) ** 2) / (axis_x**2))
    b = (((sina * (xp - x) - cosa * (yp - y)) ** 2) / (axis_y**2))

    result = a+b

    img = cv2.ellipse(img, (x, y), (axis_x, axis_y), angle, 0, 360, (255, 255, 255), 1)

    if result <= 1:
        img = cv2.circle(img, (xp, yp), 10, (255, 0, 0), -1)
        print(result)
        cv2.imwrite('/tmp/ellipse2.png', img)
        return True
    else:
        img = cv2.circle(img, (xp, yp), 10, (255, 0, 0), -1)
        print(result)
        cv2.imwrite('/tmp/ellipse2.png', img)
        return False

print(pointInEllipse(img, xCenter, yCenter, ellipse_center_x, ellipse_center_y, ellipse_axis_x, ellipse_axis_y,ellipse_angle))

enter image description here

Upvotes: 0

Views: 843

Answers (1)

mkrieger1
mkrieger1

Reputation: 23235

The cosa and sina values are wrong: math.sin and math.cos expect their arguments in radians (0 to 2π for a full circle), but you are passing an angle in degrees.

To convert an angle from degrees to radians, use the math.radians function:

angle_rad = math.radians(angle)
cosa = math.cos(angle_rad)
sina = math.sin(angle_rad)

Upvotes: 1

Related Questions