中点算法生成的圆的填充

2024-07-05 09:34:51 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中,我编写了一些代码,使用Bresenham的中点算法生成一个圆:

from PIL import Image, ImageDraw
radius = 100 #radius of circle
xpts = [] #array to hold x pts
ypts = [] #array to hold y pts
img = Image.new('RGB', (1000, 1000))
draw = ImageDraw.Draw(img) #to use draw.line()
pixels = img.load()
d = (5/4) - radius
x = 0
y = radius
xpts.append(x) #initial x value
ypts.append(y) #initial y value

while x < y:
 if d < 0:
    d += (2*x + 3)
    x += 1
    xpts.append(x + 500) #translate points to center by 500px
    ypts.append(y - 500) 
 else:
    d += (2 * (x - y) + 5)
    x += 1
    y -= 1
    xpts.append(x + 500) #translate points to center by 500px
    ypts.append(y - 500)


for i in range(len(xpts)): #draw  initial and reflected octant points
   pixels[xpts[i] ,ypts[i]] = (255,255,0) #initial octant
   pixels[xpts[i],-ypts[i]] = (255,255,0)
   pixels[-xpts[i],ypts[i]] = (255,255,0)
   pixels[-xpts[i],-ypts[i]] = (255,255,0)
   pixels[ypts[i],xpts[i]] = (255,255,0)
   pixels[-ypts[i],xpts[i]] = (255,255,0)
   pixels[ypts[i],-xpts[i]] = (255,255,0)
   pixels[-ypts[i],-xpts[i]] = (255,255,0)




img.show()

为了填充它,我计划使用ImageDraw在圆内水平绘制一条线,该线是从使用画线(). 我把x和y坐标存储在数组中。但是,我一直在解释每个点及其反射点,以便使用画线(). 有人能澄清一下吗?你知道吗


Tags: toimageimgarraypointsptsinitialdraw
2条回答

您可以使用O(n^2)中的半径radius填充圆内的所有点,而不是绘制直线:

# Your code here 

for x in range(radius):
    for y in range(radius):
        if x**2 + y**2 < radius**2:
            pixels[  x + 500 ,  y-500] = (255,255,0)
            pixels[  x + 500 , -y-500] = (255,255,0)
            pixels[ -x + 500 ,  y-500] = (255,255,0)
            pixels[ -x + 500 , -y-500] = (255,255,0)

img.show()

enter image description here

不绘制单个像素,只需添加一条线来连接彼此对应的像素(可以是-x和+x,也可以是-y和+y)。对于每个Bresenham步骤,您将绘制四条线(每条线连接两个八分音符)。你知道吗

这是您的改编样本代码。我放弃了点数组,而是直接画线。我还添加了定义圆心的cxcy变量。在代码中,有时使用负索引。这只是巧合,因为圆在中心:

from PIL import Image, ImageDraw

radius = 100  # radius of circle
xpts = []  # array to hold x pts
ypts = []  # array to hold y pts
img = Image.new('RGB', (1000, 1000))
draw = ImageDraw.Draw(img)  # to use draw.line()
pixels = img.load()
d = (5 / 4) - radius
x = 0
y = radius

cx = 500
cy = 500


def draw_scanlines(x, y):
    color = (255, 255, 0)
    draw.line((cx - x, cy + y, cx + x, cy + y), fill=color)
    draw.line((cx - x, cy - y, cx + x, cy - y), fill=color)
    draw.line((cx - y, cy + x, cx + y, cy + x), fill=color)
    draw.line((cx - y, cy - x, cx + y, cy - x), fill=color)


draw_scanlines(x, y)

while x < y:
    if d < 0:
        d += (2 * x + 3)
        x += 1
    else:
        d += (2 * (x - y) + 5)
        x += 1
        y -= 1

    draw_scanlines(x, y)

img.show()

相关问题 更多 >