gpt4 book ai didi

python - 有没有办法在 PIL 中指定矩形的宽度?

转载 作者:太空狗 更新时间:2023-10-29 16:54:16 28 4
gpt4 key购买 nike

我正在尝试使用 PIL/pillow 的 ImageDraw 模块在图像上绘制粗矩形。

我尝试使用 draw.rectangle([x1, y1, x2, y2], outline='yellow', width=3) 但它似乎不喜欢 width 参数。

我可以用一堆线条模拟我想做的事情,但我想知道是否有合适的方法。

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

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

'''

def draw_rectangle(drawing, xy, outline='yellow', width=10):
top_left = xy[0]
bottom_right = xy[1]
top_right = (xy[1][0], xy[0][1])
bottom_left= (xy[0][0], xy[1][1])

drawing.line([top_left, top_right], fill=outline, width=width)
drawing.line([top_right, bottom_right], fill=outline, width=width)
drawing.line([bottom_right, bottom_left], fill=outline, width=width)
drawing.line([bottom_left, top_left], fill=outline, width=width)

最佳答案

更新 - Pillow >= 5.3.0 rectangle 现在支持 width 参数:PIL.ImageDraw.ImageDraw.rectangle(xy,fill=None,outline=None,width=0)

上一个答案:

这是一种绘制第一个初始矩形,然后向内绘制更多矩形的方法 - 注意,线宽沿着边界居中。

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)

关于python - 有没有办法在 PIL 中指定矩形的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34255938/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com