为什么PIL-draw多边形不接受numpy数组?

2024-03-29 06:13:21 发布

您现在位置:Python中文网/ 问答频道 /正文

此代码按预期工作:

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)

但是,如果A矩阵作为numpy数组提供:

^{pr2}$

它产生了完全错误的结果。我也试着把A数组弄平,没用。在

我错过什么了吗?我能把numpy数组直接填充到PIL中吗?在


Tags: 代码fromimageimportnumpyimgnewpil
1条回答
网友
1楼 · 发布于 2024-03-29 06:13:21

如果call interface说使用元组列表或交错值列表

最好使用元组列表或交错值的序列/列表:

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


我能装东西吗

使用

>>> xy
array([[ 2,  3],
       [10,  3],
       [10,  0],
       [ 2,  0]])
>>> xy.flatten().tolist()
[ 2, 3, 10, 3, 10, 0, 2, 0 ]
>>> 

应工作并满足ImageDraw.polygon()

相关问题 更多 >