将labelme的特定标签转换成特定的mask
import json
import os
import os.path as osp
import cv2
from labelme import utils
import base64
def transJson(json_dir, spc_label=[], not_include=[], out_dir=None):
json_file = json_dir
if out_dir is None:
out_dir = osp.basename(json_file).replace('.', '_')
out_dir = osp.join(osp.dirname(json_file), out_dir)
else:
out_dir = out_dir
if not osp.exists(out_dir):
os.mkdir(out_dir)
count = os.listdir(json_file)
for i in range(0, len(count)):
path = os.path.join(json_file, count[i])
if os.path.isfile(path):
data = json.load(open(path))
if data['imageData']:
imageData = data['imageData']
else:
imagePath = os.path.join(os.path.dirname(path), data['imagePath'])
with open(imagePath, 'rb') as f:
imageData = f.read()
imageData = base64.b64encode(imageData).decode('utf-8')
img = utils.img_b64_to_arr(imageData)
label_name_to_value = {'_background_': 0}
spec_list = []
for item in data['shapes']:
if item['label'] in spc_label:
spec_list.append(item)
if item['label'] in not_include:
item['label'] = '_background_'
spec_list.append(item)
data['shapes'] = spec_list
for shape in data['shapes']:
label_name = shape['label']
if label_name in label_name_to_value:
label_value = label_name_to_value[label_name]
else:
label_value = len(label_name_to_value)
label_name_to_value[label_name] = label_value
label_values, label_names = [], []
for ln, lv in sorted(label_name_to_value.items(), key=lambda x: x[1]):
label_values.append(lv)
label_names.append(ln)
assert label_values == list(range(len(label_values)))
lbl = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)
utils.lblsave(osp.join(out_dir, count[i].replace('.json', '.png')), lbl[0])
label_png = cv2.imread(osp.join(out_dir, count[i].replace('.json', '.png')), 0)
label_png[label_png > 0] = 255
cv2.imwrite(osp.join(out_dir, count[i].replace('.json', '.png')), label_png)
print('Saved to: %s' % out_dir)
if __name__ == '__main__':
json_dir = 'E:\\CODE\\untitled1\\data\\LiverMask'
spec_labels = ['l']
not_include = ['t']
out_dir = 'E:\\CODE\\untitled1\\data\\LiverMask'
transJson(json_dir=json_dir, spc_label=spec_labels, not_include=not_include, out_dir=out_dir)
print('finished!')