Python PIL:如何在图像中间绘制椭圆? [英] Python PIL: How to draw an ellipse in the middle of an image?

查看:357
本文介绍了Python PIL:如何在图像中间绘制椭圆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎在使此代码正常工作方面遇到了一些麻烦:

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

这应该在(60,60)处绘制一个40 x 40像素的椭圆.图片什么也没返回.

This should draw an ellipse at (60,60) which is 40 by 40 pixels. The image returns nothing.

此代码可以正常工作:

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:

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

有效,但仅显示rect的一部分.而

Works, but only shows part of the rect. Whereas

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

什么也没显示.

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

This happens when drawing a rectangle too.

推荐答案

边界框是一个四元组(x0, y0, x1, y1),其中(x0, y0)是该框的左上边界,而(x1, y1)是右下角盒子的边界.

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.

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

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 eX and eY in my code snippet below).

话虽如此,下面是一个将椭圆形绘制到图像中心的代码段:

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

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

This yields the following result (1.jpg on left, output.png on right):

这篇关于Python PIL:如何在图像中间绘制椭圆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆