批量从json文件中提取每个目标,并生成对应的mask图像

        做项目测试的适合,需要把json中每个目标的mask分别提取出来保存,参考了该博主的内容,写的也挺详细的,我修改成自己需要的,将背景换成黑色,因为是分开保存,因此将mask统一定义成红色,跟将json转换成labelme_json对应的mask颜色差不多就行了,有些还需要转换成二值图,这个都很方便,可以放在项目中了,我这里就不写了。

from __future__ import division, print_function, absolute_import
import numpy as np
import os
import json
from PIL import Image,ImageDraw

color_code={}
color_code['red']='#FF0000'
color_code['black']='#000000'

def get_each_mask(jsonpath):
    for file in os.listdir(jsonpath):
        json_file = jsonpath + file
        data = json.load(open(json_file))
        img = Image.new('RGB', [640, 640], color_code['black'])
        img1 = ImageDraw.Draw(img)
        label_idx_list = list(np.arange(len(data['shapes'])))
        for i in label_idx_list:
            if data['shapes'][i]['label'] == 'A1':
                xy = []
                for xy_tuple in data['shapes'][i]['points']:
                    xy += xy_tuple
                img1.polygon(xy, fill=color_code['red'], outline=color_code['red'])
                label_idx_list.remove(i)    
        img.save(r'I:/footimage/paperlen/len/foot_mask/'+ os.path.splitext(file)[0] + '.png')

    for file in os.listdir(jsonpath):
        json_file = jsonpath + file
        data = json.load(open(json_file))
        img = Image.new('RGB', [640, 640], color_code['black'])
        img2 = ImageDraw.Draw(img)
        label_idx_list = list(np.arange(len(data['shapes'])))
        for i in label_idx_list:
            if data['shapes'][i]['label'] == 'A2':
                xy = []
                for xy_tuple in data['shapes'][i]['points']:
                    xy += xy_tuple
                img2.polygon(xy, fill=color_code['red'], outline=color_code['red'])
                label_idx_list.remove(i) 
        img.save(r'I:/footimage/paperlen/len/paper_mask/'+ os.path.splitext(file)[0] + '.png')
        
        
        
if __name__=='__main__':
    jsonpath=r'I:/footimage/paperlen/len/json/'
    get_each_mask(jsonpath)
    

 

你可能感兴趣的:(detectron2,json)