Python 给定半径和圆心的圆上的所有点

Python all points on circle given radius and center

我写了这个函数:

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

'circles' 是一个数组 [X-center, Y-center, Radius]

我想提取圆中所有 整数分辨率 的点。 现在,我意识到我正在创建一个位于圆边界上的点数组,但我无法访问圆内的点。

我想到的只是减小半径,并对半径的所有值进行迭代,直到半径为 0

但我觉得还有更有效的方法。欢迎任何帮助

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)]

使用 numpy

import numpy as np
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),))

任意中心

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