Python PIL:如何在图像中间绘制椭圆?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4789894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python PIL: How to draw an ellipse in the middle of an image?
提问by Tommo
I seem to be having some trouble getting this code to work:
我似乎在使用此代码时遇到了一些麻烦:
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()
This should draw an ellipse at (60,60) which is 40 by 40 pixels. The image returns nothing.
这应该在 (60,60) 处绘制一个 40 x 40 像素的椭圆。图像不返回任何内容。
This code works fine however:
但是,此代码工作正常:
draw.ellipse ((0,0,40,40), fill=128)
It just seems that when i change the first 2 co-ords (for where the ellipse should be placed) it won't work if they are larger than the size of the ellipse to be drawn. For example:
似乎当我更改前 2 个坐标(用于放置椭圆的位置)时,如果它们大于要绘制的椭圆的大小,它将不起作用。例如:
draw.ellipse ((5,5,15,15), fill=128)
Works, but only shows part of the rect. Whereas
有效,但只显示矩形的一部分。然而
draw.ellipse ((5,5,3,3), fill=128)
shows nothing at all.
什么都不显示。
This happens when drawing a rectangle too.
绘制矩形时也会发生这种情况。
采纳答案by sahhhm
The bounding box is a 4-tuple (x0, y0, x1, y1)where (x0, y0)is the top-left bound of the box and (x1, y1)is the lower-right bound of the box.
边界框是一个四元组(x0, y0, x1, y1),其中(x0, y0)是框的左上边界, 是框(x1, y1)的右下边界。
To draw an ellipse to the center of the image, you need to define how large you want your ellipse's bounding box to be (variables eXand eYin my code snippet below).
要将椭圆绘制到图像的中心,您需要定义您希望椭圆的边界框有多大(变量eX和eY下面的代码片段)。
With that said, below is a code snippet that draws an ellipse to the center of an image:
话虽如此,下面是一个在图像中心绘制椭圆的代码片段:
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()
This yields the following result (1.jpgon left, output.pngon right):
这会产生以下结果(1.jpg左侧,output.png右侧):




回答by Unoti
The ellipse function draws an ellipse within a bounding box. So you need to use draw.ellipse((40,40,60,60))or other coordinates where the top left is smaller than the bottom right.
ellipse 函数在边界框内绘制一个椭圆。因此,您需要使用draw.ellipse((40,40,60,60))或其他坐标,其中左上角小于右下角。

