标注的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)