2015-12-13 8 views
8

Ich versuche, dicke Rechtecke auf ein Bild mit ImageDraw Module von PIL/Kissen zu zeichnen.Gibt es eine Möglichkeit, die Breite eines Rechtecks ​​in PIL anzugeben?

Ich versuchte mit draw.rectangle([x1, y1, x2, y2], outline='yellow', width=3), aber es scheint nicht die Breite Parameter.

Ich kann emulieren, was ich mit einer Reihe von Zeilen tun möchte, aber ich frage mich, ob es eine richtige Art und Weise zu tun ist.

''' 
coordinates = [x1, y1, x2, y2] 

    (x1, y1) 
     *-------------- 
     |    | 
     |    | 
     |    | 
     |    | 
     |    | 
     |    | 
     --------------* 
         (x2, y2) 

''' 
def draw_rectangle(drawing, coordinates, color='yellow', width=3): 
    #top 
    line_coordinates = [coordinates[0], coordinates[1], coordinates[2], coordinates[1]] 
    drawing.line(line_coordinates, fill=color, width=width) 

    #left 
    line_coordinates = [coordinates[0], coordinates[1], coordinates[0], coordinates[3]] 
    drawing.line(line_coordinates, fill=color, width=width) 

    #right 
    line_coordinates = [coordinates[2], coordinates[1], coordinates[2], coordinates[3]] 
    drawing.line(line_coordinates, fill=color, width=width) 

    #bottom 
    line_coordinates = [coordinates[0], coordinates[3], coordinates[2], coordinates[3]] 
    drawing.line(line_coordinates, fill=color, width=width) 

Antwort

5

PIL rectangle der nicht unterstützt das width Argument.

Ich schrieb eine ineffiziente Methode gut für nur herumspielen - aber beachten Sie, die Linienbreite ist nicht zentriert entlang der Grenze.

def draw_rectangle(draw, coordinates, color, width=1): 
    for i in range(width): 
     rect_start = (coordinates[0][0] - i, coordinates[0][1] - i) 
     rect_end = (coordinates[1][0] + i, coordinates[1][1] + i) 
     draw.rectangle((rect_start, rect_end), outline = color) 

# example usage 

im = Image.open(image_path) 
drawing = ImageDraw.Draw(im) 

top_left = (50, 50) 
bottom_right = (100, 100) 

outline_width = 10 
outline_color = "black" 

draw_rectangle(drawing, (top_left, bottom_right), color=outline_color, width=outline_width) 
0

Sie können eine Ansicht zeichnen Rects z.B:

draw.rectangle([(x, y),(x+w,y+h) ], outline=(0,0,255,255)) 
draw.rectangle([(x+1, y+1),(x+w-1,y+h-1) ], outline=(0,0,255,255)) 
draw.rectangle([(x+2, y+2),(x+w-2,y+h-2) ], outline=(0,0,255,255)) 
... 

von Ursache in einer Schleife und einer Funktion.