Python PIL:如何在图像中间绘制椭圆?

2024-05-16 01:44:16 发布

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

我似乎在让代码工作时遇到了一些问题:

import Image, ImageDraw

im = Image.open("1.jpg")

draw = ImageDraw.Draw(im)
draw.ellipse((60, 60, 40, 40), fill=128)
del draw 

im.save('output.png')
im.show()

这应该在(60,60)处画一个40×40像素的椭圆。图像不返回任何内容。

此代码工作正常,但是:

draw.ellipse ((0,0,40,40), fill=128)

当我改变前两个单词(椭圆应该放在哪里)时,如果它们大于要画的椭圆的大小,就不起作用了。例如:

draw.ellipse ((5,5,15,15), fill=128)

有效,但仅显示部分矩形。鉴于

draw.ellipse ((5,5,3,3), fill=128)

一点也不显示。

绘制矩形时也会发生这种情况。


Tags: 代码imageimportsaveopenfilljpg椭圆
2条回答

椭圆函数在边界框中绘制椭圆。所以需要使用draw.ellipse((40,40,60,60))或其他左上角小于右下角的坐标。

边界框是一个4元组(x0, y0, x1, y1),其中(x0, y0)是框的左上边界,(x1, y1)是框的右下边界。

要将椭圆绘制到图像的中心,需要定义椭圆的边界框的大小(下面的代码片段中的变量eXeY)。

尽管如此,下面是一个代码片段,它将椭圆绘制到图像的中心:

from PIL import Image, ImageDraw

im = Image.open("1.jpg")

x, y =  im.size
eX, eY = 30, 60 #Size of Bounding Box for ellipse

bbox =  (x/2 - eX/2, y/2 - eY/2, x/2 + eX/2, y/2 + eY/2)
draw = ImageDraw.Draw(im)
draw.ellipse(bbox, fill=128)
del draw

im.save("output.png")
im.show()

这将产生以下结果(1.jpg在左侧,output.png在右侧):

1.jpgoutput.png

相关问题 更多 >