首页 > 解决方案 > 如何使用 features.rasterize 在 Python 3 中创建遮罩图像?

问题描述

目前,我使用以下代码来创建蒙版图像(classes = ['tree', 'car', 'bicycle'],polygons是几何对象的列表,其中每个几何对象具有coordinates定义图像上的多边形的字段,该多边形是类对象的边界框):

def create_mask(self, mask_size, classes, polygons):
    # type (Tuple[int, int], List[str], List[geometry]) -> Image
    # Create a new palette image, the default color of Image.new() is black
    # https://pillow.readthedocs.io/en/3.3.x/handbook/concepts.html#modes
    img = Image.new('P', mask_size)
    img.putpalette(self.palette) # palette = [0, 0, 0, 255, 0, 0, ...]
    draw = ImageDraw.Draw(img)
    for i, class_ in enumerate(classes):
        color_index = self.class_to_color_index[class_]
        draw.polygon(xy=polygons[i].exterior.coords, fill=color_index)
    del draw
    return img

有没有办法用 using 重写这段代码features.rasterize

标签: python-3.xpython-imaging-library

解决方案


推荐阅读