Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PIL draw polygon does not accept numpy array?

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?

like image 564
matousc Avatar asked Oct 24 '25 16:10

matousc


1 Answers

If call-interaface says use a list-of-tuples or a list of interleaved values,

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, ...].


Can I stuff ..

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()

like image 166
user3666197 Avatar answered Oct 26 '25 06:10

user3666197



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!