Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python PIL: How to draw an ellipse in the middle of an image?

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.

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:

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.

like image 259
Tommo Avatar asked Jan 25 '11 04:01

Tommo


People also ask

How do you manually draw an ellipse?

A vertical line is drawn from the center of the bottom line receding towards the vanishing point. A horizontal line is drawn across the middle of the "square". These two lines will intersect at the middle of what will become the ellipse.

How do you draw a rectangle on the PIL image in Python?

rectangle() Draws an rectangle. Parameters: xy – Four points to define the bounding box. Sequence of either [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].

How do you display the PIL of an image in Python?

Python – Display Image using PIL To show or display an image in Python Pillow, you can use show() method on an image object. The show() method writes the image to a temporary file and then triggers the default program to display that image. Once the program execution is completed, the temporary file will be deleted.


1 Answers

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.

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

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

1.jpgoutput.png

like image 156
sahhhm Avatar answered Sep 21 '22 12:09

sahhhm