I would like to draw an arbitrary ellipse on an opencv image in python and then return two arrays: (1) The pixel coordinates of all pixels bounded by the ellipse, both on the ellipse line and inside the ellipse, (2) the pixel values of each of the pixels from array (1).
I looked at this answer, but it only considers the points on the ellipse contour and not the region inside.
CodePudding user response:
With this code you can get every pixel inside an ellipse:
from math import sin, cos
def get_y_ellipse(ellipse_size, x, alpha):
a, b = ellipse_size[0] / 2, ellipse_size[1] / 2
delta_sqrt = ((b**4-2*a**2*b**2 a**4)*sin(2*alpha)**2*x**2-4*a**4*x**2*cos(alpha)**2*sin(alpha)**2-4*a**2*b**2*x**2*cos(alpha)**2 4*a**4*b**2*cos(alpha)**2-4*a**2*b**2*x**2*sin(alpha)**4-4*b**4*x**2*sin(alpha)**2*cos(alpha)**2 4*a**2*b**4*sin(alpha)**2)**(1/2)
y1 = ((-b**2 a**2)*sin(2*alpha)*x delta_sqrt) / (2*a**2*cos(alpha)**2 2*b**2*sin(alpha)**2)
y2 = ((-b**2 a**2)*sin(2*alpha)*x - delta_sqrt) / (2*a**2*cos(alpha)**2 2*b**2*sin(alpha)**2)
return y1, y2
ellipse_size = (100, 50)
ellipse_rotation = 45 # deg
ellipse_center_position = (0,0)
pixels = []
for x in range(ellipse_center_position[0] - ellipse_size[0], ellipse_center_position[0] ellipse_size[0]):
y1, y2 = get_y_ellipse(ellipse_size, x, ellipse_rotation)
if complex not in map(type, (y1, y2)):
for y in range(int(y1), int(y2), -1):
pixels.append([x, y])
# 'pixels' is a 1d array that contain every pixel [x,y] format
Hope this helps.