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

后端 未结 2 1683
后悔当初
后悔当初 2020-12-14 23:34

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,          


        
相关标签:
2条回答
  • 2020-12-14 23:38

    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.

    0 讨论(0)
  • 2020-12-14 23:43

    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.jpg output.png

    0 讨论(0)
提交回复
热议问题