以下是批量处理案例代码

def json2mask(json_path):
    # 定制类别着色字典
    color_dict = {
        '0': 255,
        '1': 200,
        '2': 150,
        '3': 100,
        '4': 50
    }

    with open(json_path, 'r', encoding='utf-8') as file:
        data = json.load(file)
    
        image_width = data['imageWidth']
        image_height = data['imageHeight']

        binary_image = Image.new('L', (image_width, image_height), 0)
        draw = ImageDraw.Draw(binary_image)

        # 防止空文件干扰
        flag = True
        if len(data['shapes']) == 0:
            flag =  False

        # 读取多个掩码区域
        for i in range(len(data['shapes'])):
            polygon_points = data['shapes'][i]['points']

            polygon_points = np.round(polygon_points).astype(int)
            polygon_points = [tuple(item) for item in polygon_points]
            draw.polygon(polygon_points, fill=color_dict[data['shapes'][i]['label']], outline=None)

        return binary_image, flag