Skip to content

ImageDraw.line and Coords typing issue #8798

@Andrej730

Description

@Andrej730

ImageDraw.line is currently using Coords for xy argument.

xy: Coords,

Coords = Union[Sequence[float], Sequence[Sequence[float]]]

Coords allows Sequence[Sequence], so it should support both tuple[tuple] and list[list] but currently it doesn't seem to be the case with ImageDraw.line - it fails with list[list] at runtime though there are no typing errors.

See example below.

from PIL import Image, ImageDraw
import numpy as np

img_size = (200, 200)
scale = 1.0

img = Image.new("RGB", img_size, "white")
draw = ImageDraw.Draw(img)

verts = np.array(
    [
        [[22.0, 105.0], [114.0, 105.0]],
        [[22.0, 105.0], [22.0, 23.0]],
        [[114.0, 105.0], [114.0, 113.0]],
        [[114.0, 113.0], [14.0, 113.0]],
        [[14.0, 113.0], [14.0, 15.0]],
        [[14.0, 15.0], [114.0, 15.0]],
        [[114.0, 15.0], [114.0, 23.0]],
        [[114.0, 23.0], [22.0, 23.0]],
    ]
)

for verts_ in verts:
    lst: list[list[float]]
    lst = verts_.tolist()
    # No typing errors but fails at runtime.
    # Traceback (most recent call last):
    # File "second_test.py", line 28, in <module>
    #     draw.line(verts_.tolist(), fill="black", width=2)
    # File "\Lib\site-packages\PIL\ImageDraw.py", line 249, in line
    #     self.draw.draw_lines(xy, ink, width)
    # ValueError: incorrect coordinate type
    # draw.line(lst, fill="black", width=2)

    # Works fine, list of tuples also work fine too.
    tple = tuple(tuple(i) for i in verts_)
    draw.line(tple, fill="black", width=2)

# Show the image
img.show()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions