如何在Python 3中使用features.rasterize创建遮罩图像?

时间:2019-04-14 21:02:10

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

当前,我使用以下代码创建蒙版图像(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

是否可以使用features.rasterize重写这段代码?

0 个答案:

没有答案