def frame_to_mask(
        out_path: str,
        shape: ImageSize,
        colors: List[NDArrayU8],
        poly2ds: List[List[Poly2D]],
        with_instances: bool=True,
        back_color: int=0,
        closed: bool=True, ) -> None:
    """Converting a frame of poly2ds to mask/bitmask."""
    assert len(colors) == len(poly2ds)
    height, width = shape.height, shape.width

    assert back_color >= 0
    if with_instances:
        img: NDArrayU8 = (
            np.ones(
                [height, width, 4], dtype=np.uint8) * back_color  # type: ignore
        )
    else:
        img = (
            np.ones(
                [height, width, 1], dtype=np.uint8) * back_color  # type: ignore
        )

    if len(colors) == 0:
        pil_img = Image.fromarray(img.squeeze())
        pil_img.save(out_path)

    matplotlib.use("Agg")
    fig = plt.figure(facecolor="0")
    fig.set_size_inches((width / fig.get_dpi()), height / fig.get_dpi())
    ax = fig.add_axes([0, 0, 1, 1])
    ax.axis("off")
    ax.set_xlim(0, width)
    ax.set_ylim(0, height)
    ax.set_facecolor((0, 0, 0, 0))
    ax.invert_yaxis()

    for i, poly2d in enumerate(poly2ds):
        for poly in poly2d:
            ax.add_patch(
                poly_to_patch(
                    poly.vertices,
                    poly.types,
                    # (0, 0, 0) for the background
                    color=(
                        ((i + 1) >> 8) / 255.0,
                        ((i + 1) % 255) / 255.0,
                        0.0, ),
                    closed=closed, ))

    fig.canvas.draw()
    out: NDArrayU8 = np.frombuffer(fig.canvas.tostring_rgb(), np.uint8)
    out = out.reshape((height, width, -1)).astype(np.int32)
    out = (out[..., 0] << 8) + out[..., 1]
    plt.close()

    for i, color in enumerate(colors):
        # 0 is for the background
        img[out == i + 1] = color

    img[img == 255] = 0

    pil_img = Image.fromarray(img.squeeze())
    pil_img.save(out_path)
Converting a frame of poly2ds to mask/bitmask.
deploy/pipeline/tools/lane_to_mask.py