Mask图像与json文件相互转换

做机器学习处理图像时,需要标注图像,其中一种标注是标出图像中的某些区域,生成Mask图像或记录下这些区域的轮廓点坐标。通常,标注直接生成其中一种文件,即只生成json文件或只生成Mask图像。故在此贴出Mask图像与json文件相互转换的Python代码。

mask_to_json

import cv2
import os
import json
import sys


def func(file:str) -> dict:
    png = cv2.imread(file)
    gray = cv2.cvtColor(png, cv2.COLOR_BGR2GRAY)
    _, binary = cv2.threshold(gray,10,255,cv2.THRESH_BINARY)
    contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    dic = {"version": "5.0.1", "flags": {},"shapes":list(), "imagePath":os.path.basename(file),
            "imageHeight":png.shape[0], "imageWidth":png.shape[1]}
    for contour in contours:
        temp = list()
        for point in contour[2:]:
            if len(temp) > 1 and temp[-2][0] * temp[-2][1] * int(point[0][0]) * int(point[0][1]) != 0 and (int(point[0][0]) - temp[-2][0]) * (
                            temp[-1][1] - temp[-2][1]) == (int(point[0][1]) - temp[-2][1]) * (temp[-1][0] - temp[-1][0]):
                temp[-1][0] = int(point[0][0])
                temp[-1][1] = int(point[0][1])
            else:
                temp.append([int(point[0][0]), int(point[0][1])])
        dic["shapes"].append({"label": "result", "points":temp, "group_id": None,
                                "shape_type": "polygon", "flags": {}})

    return dic


if  __name__ == "__main__":

    if len(sys.argv) != 3:
        raise ValueError("mask文件或目录 输出路径")

    if os.path.isdir(sys.argv[1]):
        for file in os.listdir(sys.argv[1]):
            with open(os.path.join(sys.argv[2], os.path.splitext(file)[0]+".json"), mode='w', encoding="utf-8") as f:
                json.dump(func(os.path.join(sys.argv[1], file)), f)
    else:
        with open(os.path.join(sys.argv[2], os.path.splitext(os.path.basename(sys.argv[1]))[0]+".json"), mode='w', encoding="utf-8") as f:
            json.dump(func(sys.argv[1]), f)

json_to_mask

import cv2
import json
import numpy as np
import os
import sys


def func(file:str) -> np.ndarray:
    with open(file, mode='r', encoding="utf-8") as f:
        configs = json.load(f)
    shapes = configs["shapes"]

    png = np.zeros((configs["imageHeight"], configs["imageWidth"], 3), np.uint8)

    for shape in shapes:
        cv2.fillPoly(png, [np.array(shape["points"], np.int32)], (0,0,255))

    return png


if  __name__ == "__main__":

    if len(sys.argv) != 3:
        raise ValueError("json文件或目录 输出路径")

    if os.path.isdir(sys.argv[1]):
        for file in os.listdir(sys.argv[1]):
            cv2.imwrite(os.path.join(sys.argv[2], os.path.splitext(file)[0]+".png" ), func(os.path.join(sys.argv[1], file)))
    else:
        cv2.imwrite(os.path.join(sys.argv[2], os.path.splitext(os.path.basename(sys.argv[1]))[0]+".png"), func(sys.argv[1]))

使用方法:在命令行中输入

python json_to_mask.py 文件夹或json文件 输出文件夹

python mask_to_json.py 文件夹或mask图片 输出文件夹

如果输入文件夹,则会将文件夹下所有json文件或mask图片转成对应文件输出到指定路径中。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2023年8月9日
下一篇 2023年8月9日

相关推荐