json转mask

标注的json数据文件转换为图像的掩码

import numpy as np
from json import load
import cv2
from pathlib import Path


def json_to_mask(json_path, mask_path):
    """
    标注的json数据文件转换为图像的掩码
    """
    h, w = 640, 960
    mask = np.zeros([h, w, 1], np.uint8)
    with open(json_path, "r", encoding='utf-8') as f:
        json_labels = load(f)
        json_shapes = json_labels["shapes"]
        if json_shapes:
            for shape in json_shapes:
                points = shape["points"]
                # 填充
                points_array = np.array(points, dtype=np.int32)
                mask = cv2.fillPoly(mask, [points_array], 255)
                
            cv2.imencode('.png', mask)[1].tofile(
                mask_path
            )
        else:
            image_name = json_path.stem
            print(image_name)
        
if __name__ == "__main__":
    image_dir_path = Path(
        "./images"
    )
    json_path_list = list(image_dir_path.glob(f"*.json"))
    mask_dir_path = Path("./masks")
    mask_dir_path.mkdir(exist_ok=True)
    for json_path in json_path_list:
        mask_name = "".join((json_path.stem, ".png"))
        mask_path = mask_dir_path.joinpath(mask_name)
        json_to_mask(json_path, mask_path)
    
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值