我正在尝试使用PIL /枕头的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)
更新 - 枕头> = 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)
您也可以使用四个点绘制一条线而不是四条线,从而形成一个矩形:
def drawrect(drawcontext, xy, outline=None, width=0):
(x1, y1), (x2, y2) = xy
points = (x1, y1), (x2, y1), (x2, y2), (x1, y2), (x1, y1)
drawcontext.line(points, fill=outline, width=width)
# example
from PIL import Image, ImageDraw
im = Image.new("RGB", (150, 150), color="white")
draw = ImageDraw.Draw(im)
drawrect(draw, [(50, 50), (100, 100)], outline="red", width=5)
im.show()
PIL矩形现在支持width
参数。
from PIL import Image, ImageDraw
height = width = 800
img = Image.new('RGB', (height, width), (255, 255, 255))
draw = ImageDraw.Draw(img)
draw.rectangle([100,100,500,400], width = 10, outline="#0000ff")
img.show()
这种方法适用于Ubuntu 18.04上的PIL v1.1.7和枕头v 5.3.0。角落不是正方形,但至少仅偏离1/2像素,而不是绘制具有宽度参数的4条线以创建矩形的方法,每个角落偏离至少1个像素。我认为枕头/ pil中的线条绘制算法仍然存在错误。
def drawrect(drawcontext, xy, color=None, width=1):
(x1, y1), (x2, y2) = xy
offset = 1
for i in range(0, width):
drawcontext.rectangle(((x1, y1), (x2, y2)), outline=color)
x1 = x1 - offset
y1 = y1 + offset
x2 = x2 + offset
y2 = y2 - offset
然后在你的代码中你会有:
# example
from PIL import Image, ImageDraw
im = Image.new("RGB", (150, 150), color="white")
draw = ImageDraw.Draw(im)
drawrect(draw, [(50, 50), (100, 100)], outline="red", width=5)
del draw
im.show()
感谢gdwarf的解决方案让我走上了这条路。
您可以绘制视图,例如:
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))
...
循环和函数中的原因。