Python all points on circle given radius and center

13,974
from itertools import product
def points_in_circle(radius):
    for x, y in product(range(int(radius) + 1), repeat=2):
        if x**2 + y**2 <= radius**2:
            yield from set(((x, y), (x, -y), (-x, y), (-x, -y),))
list(points_in_circle(2))
[(0, 0), (0, 1), (0, -1), (0, -2), (0, 2), (1, 0), (-1, 0), (-1, 1), (1, -1), (1, 1), (-1, -1), (2, 0), (-2, 0)]

with numpy

def points_in_circle_np(radius):
    a = np.arange(radius + 1)
    for x, y in zip(*np.where(a[:,np.newaxis]**2 + a**2 <= radius**2)):
        yield from set(((x, y), (x, -y), (-x, y), (-x, -y),))

with arbitrary center

def points_in_circle_np(radius, x0=0, y0=0, ):
    x_ = np.arange(x0 - radius - 1, x0 + radius + 1, dtype=int)
    y_ = np.arange(y0 - radius - 1, y0 + radius + 1, dtype=int)
    x, y = np.where((x_[:,np.newaxis] - x0)**2 + (y_ - y0)**2 <= radius**2)
    # x, y = np.where((np.hypot((x_-x0)[:,np.newaxis], y_-y0)<= radius)) # alternative implementation
    for x, y in zip(x_[x], y_[y]):
        yield x, y
Share:
13,974

Related videos on Youtube

aze45sq6d
Author by

aze45sq6d

Updated on June 04, 2022

Comments

  • aze45sq6d
    aze45sq6d almost 2 years

    I wrote this function:

    def get_x_y_co(circles):
        xc = circles[0] #x-co of circle (center)
        yc = circles[1] #y-co of circle (center)
        r = circles[2] #radius of circle
        arr=[]
        for i in range(360):
            y = yc + r*math.cos(i)
            x = xc+ r*math.cos(i)
            x=int(x)
            y=int(y)
            #Create array with all the x-co and y-co of the circle
            arr.append([x,y])
        return arr
    

    With 'circles' being an array with [X-center, Y-center, Radius]

    I would like to extract all the points with integer resolution present in the circle. Right now, I realised I am creating an array of points who are on the BORDER of the circle, but I don't have access to the points INSIDE the circle.

    I thought of just reducing the radius, and iterate this for all values of the radius, until the radius is 0

    But I feelthere is a much more efficient way. Any help is welcome

    • khelwood
      khelwood about 6 years
      Aren't there an infinite number of points inside the circle?
    • aze45sq6d
      aze45sq6d
      Yes I do, but I have an exercise asking to calculate the average color of the circle just given the radius and the center coords. I was thinking of just extracting all the pixels in the circle, and then calculating the mean value of the BGR values
    • DeepSpace
      DeepSpace
      See stackoverflow.com/questions/15856411/… Not in Python but can be easily ported.
    • khelwood
      khelwood
      I guess you mean points with integer resolution?