自学内容网 自学内容网

多个分割对象,读取jsons 文件夹,然后先分割大目标再分割小目标分割,一张图多个分割目标mask

import json, os
import argparse
import numpy as np
import PIL.Image
import PIL.ImageDraw
import shutil
import glob


def get_color_map_list(num_classes):
    """
    Returns the color map for visualizing the segmentation mask,
    which can support arbitrary number of classes.
    Args:
        num_classes (int): Number of classes.
    Returns:
        (list). The color map.
    """
    
    num_classes += 1
    color_map = num_classes * [0, 0, 0]
    for i in range(0, num_classes):
        j = 0
        lab = i
        while lab:
            color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j))
            color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j))
            color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j))
            j += 1
            lab >>= 3
    color_map = color_map[3:]
    return color_map


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Json FIle To Mask Image")
    parser.add_argument("--json_dir", default="F:\\DVC_data\\abdomen_images3\\jsons", type=str, help="path of the mask image")
    parser.add_argument("--json_list", default="train.txt", type=str, help="path of the mask image")
    parser.add_argument("--label", default="pin", type=str, help="the label name in json file")
    parser.add_argument("--save_dir", default="./mask", type=str, help="path of the mask image")
    args = parser.parse_args()

    # fp_list = open(args.json_list, 'r')
    # 为每个分割区域分配一个随机颜色
    color_map = get_color_map_list(256)
    n=0
    for line in glob.glob("F:\\DVC_data\\abdomen_images3\\jsons\\*.json" ):  #  "D:\\data\\胆囊分割\\jsons\\*.json"
        line = line.strip()
        json_path = os.path.join(args.json_dir, line)
        mask_path = os.path.join(args.save_dir, line.replace('json', 'jpg'))
        f = open(json_path, encoding='utf-8')
        json_info = json.load(f)
        shapes = json_info['shapes']
        
        height = json_info['imageHeight']
        width = json_info['imageWidth']
        img_name = json_info['imagePath']

        mask = np.zeros((height, width), dtype=np.uint8)
        mask = PIL.Image.fromarray(mask,mode='P')  #mode='P' 伪颜色图的保存设置,否则显示不了不同颜色
        draw = PIL.ImageDraw.Draw(mask)

        have_lab = 0
        have_2=0
        # 根据轮廓大小对label进行排序,, 大的轮廓在前面,小的轮廓在后面
        # shapes = sorted(shapes, key=lambda x: len(x['points']), reverse=True)
        # 根据名字排序,胆囊壁放在第一位,胆囊放在第二位,其他的标签任意位置,,所以先处理胆囊壁,大的轮廓分割,然后是小的
        shapes = sorted(shapes, key=lambda x: 0 if x["label"] == "胆囊壁" else 1 if x["label"] == "胆囊" else 2)
        # 或者这张图先胆囊壁,处理完,再循环一遍,胆囊处理一遍,得到的就是复合的分割图片
        for i in range(len(shapes)):
            shape = shapes[i]
            shape_type = shape['shape_type']
            label = shape['label']
            if shape_type == 'polygon' and label == "胆囊壁": #大的圈,填充值是2
                points = shape['points']
                xy = [tuple(point) for point in points]
                draw.polygon(xy=xy, outline=2, fill=2)
                have_lab = 1
                have_2+=1
                
        for i in range(len(shapes)):
            shape = shapes[i]
            shape_type = shape['shape_type']
            label = shape['label']
            if shape_type == 'polygon' and label == "胆囊":  #小的圈是填充值1,  先打后小,因为一个位置不会是两个分类
            # 保存伪颜色 mask  ,多个对象拼接好了之后,像素值不变还是0,1,2  #
                points = shape['points']
                xy = [tuple(point) for point in points]
                draw.polygon(xy=xy, outline=1, fill=1)  # 胆囊是  内部的一层是1,背景默认是 0
                have_lab = 1
                have_2 += 1
          
        
        root = "D:\\data\\胆囊分割\\"
        if have_2==2:
            n=n+1
            mask.putpalette(color_map)
            mask.save(root+"masks\\" + img_name)

            json_name = img_name.replace("png","json")
            shutil.copy("F:\\DVC_data\\abdomen_images3\\jsons\\"+json_name, root+"jsons\\"+json_name)

            shutil.copy("F:\\DVC_data\\abdomen_images3\\images\\"+img_name, root+"images\\"+img_name)
            print(n)
            print(img_name)

在这里插入图片描述


原文地址:https://blog.csdn.net/m0_37192554/article/details/137685417

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!