像素网格中的圆圈

时间:2015-07-20 14:36:16

标签: python numpy graphics

鉴于中心(x,y)和半径r,如何使用python在像素网格中绘制圆C((x,y),r)?可以假设像素网格足够大。

2 个答案:

答案 0 :(得分:5)

这里是Python中的RosettaCode Midpoint circle algorithm

def circle(self, x0, y0, radius, colour=black):
    f = 1 - radius
    ddf_x = 1
    ddf_y = -2 * radius
    x = 0
    y = radius
    self.set(x0, y0 + radius, colour)
    self.set(x0, y0 - radius, colour)
    self.set(x0 + radius, y0, colour)
    self.set(x0 - radius, y0, colour)

    while x < y:
      if f >= 0: 
        y -= 1
        ddf_y += 2
        f += ddf_y
        x += 1
        ddf_x += 2
        f += ddf_x    
        self.set(x0 + x, y0 + y, colour)
        self.set(x0 - x, y0 + y, colour)
        self.set(x0 + x, y0 - y, colour)
        self.set(x0 - x, y0 - y, colour)
        self.set(x0 + y, y0 + x, colour)
        self.set(x0 - y, y0 + x, colour)
        self.set(x0 + y, y0 - x, colour)
        self.set(x0 - y, y0 - x, colour)
        Bitmap.circle = circle

        bitmap = Bitmap(25,25)
        bitmap.circle(x0=12, y0=12, radius=12)
        bitmap.chardisplay()

答案 1 :(得分:4)

假设你想完成任务(而不是学习光栅图形算法),只需使用Pillow

from PIL import Image, ImageDraw
image = Image.new('1', (10, 10)) #create new image, 10x10 pixels, 1 bit per pixel
draw = ImageDraw.Draw(image)
draw.ellipse((2, 2, 8, 8), outline ='white')
print list(image.getdata())

输出:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 0, 0, 0, 255, 255, 0, 0, 0, 255, 0, 0, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 0, 0, 255, 0, 0, 0, 255, 255, 0, 0, 0, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

范围是0..255,因为Pillow甚至为每像素1位图像存储每像素一个字节(因为它更有效)。

如果您希望范围为0..1,则可以除以255:

[x/255 for x in image.getdata()]