Reputation: 3977
This code works as expected:
import numpy as np
from PIL import Image, ImageDraw
A = (
( 2, 2),
( 2, 302),
( 302, 302),
( 302, 2)
)
img = Image.new('L', (310, 310), 0)
ImageDraw.Draw(img).polygon(A, outline=1, fill=1)
mask = np.array(img)
print(mask)
However, if the A matrix is provided as numpy array:
A = np.array(
[[ 2, 2],
[ 2, 302],
[302, 302],
[302, 2]], dtype="int32"
)
it produces completely wrong result. I also try to flatten the A array, it does not help.
Do I miss something? Can I stuff the numpy array somehow directly into PIL?
Upvotes: 4
Views: 2508
Reputation: 1
best use a list-of-tuples or a sequence / list of interleaved values:
PIL.ImageDraw.ImageDraw.polygon( xy, fill = None, outline = None )
Draws a polygon.The polygon outline consists of straight lines between the given coordinates, plus a straight line between the last and the first coordinate.
xy
– Sequence of
either
2-tuples like[(x, y), (x, y), ...]
or
numeric values like[x, y, x, y, ...]
.
Using
>>> xy
array([[ 2, 3],
[10, 3],
[10, 0],
[ 2, 0]])
>>> xy.flatten().tolist()
[ 2, 3, 10, 3, 10, 0, 2, 0 ]
>>>
shall work and meet the PIL-documented-Call-Interface for ImageDraw.polygon()
Upvotes: 7