JSON2Mask

import json
from PIL import Image
from PIL import ImageDraw
import PIL
import os
import numpy as np
from labelme import utils
import imgviz
import yaml


jsonfolder = './JSON/'
out_folder = 'labelme_json'

jsonfiles = os.listdir(jsonfolder)
for jsonfile in jsonfiles:
	name, ext = os.path.splitext(jsonfile)
	if ext != '.json':
		continue

	out_dir = os.path.join(out_folder, name)
	if not os.path.exists(out_dir):
		os.makedirs(out_dir)
	
	with open(jsonfolder + jsonfile,'r') as jf:
		labels = json.load(jf)
		shapes = labels['shapes']

		imageData = labels.get('imageData')

		# print(imageData.shape)
		img = utils.img_b64_to_arr(imageData)
		# print(img.shape)


		img_shape = img.shape
		# print('img_shape:', img_shape)

		ins_mask = np.zeros(img_shape[:2], dtype=np.uint8)
		ins_mask = PIL.Image.fromarray(ins_mask)
		label_names = ['__background__']
		
		objects = {}
		
		for j, region in enumerate(shapes):
			points = region['points']
			label_name = region['label']

			if label_name not in objects:
				objects[label_name] = []
				
			objects[label_name].append(points)

		j = 0
		for label_name, points_list in objects.items():
			for points in points_list:
				xy = [tuple(point) for point in points]
				draw = ImageDraw.Draw(ins_mask)
				draw.polygon(xy, outline=j+1, fill=j+1)
			label_names.append(label_name)
			j+=1

		lbl = np.array(ins_mask)

		save_img = PIL.Image.fromarray(img)

		# save_lbl = PIL.Image.fromarray(lbl)


		if img_shape[0] != 512 or img_shape[1] != 512:
			save_img = save_img.resize((512,512))
			# save_lbl = lbl.resize((512,512))
			lbl.reshpe(512,512)

		# PIL.Image.fromarray(img).save(os.path.join(out_dir, "img.png"))
		save_img.save(os.path.join(out_dir, "img.png"))

		utils.lblsave(os.path.join(out_dir, "label.png"), lbl)

		# with Image.open(filename) as image:

		# lbl_viz = imgviz.label2rgb(label=lbl, img=imgviz.asgray(img), label_names=label_names, loc="rb")
		# PIL.Image.fromarray(lbl_viz).save(os.path.join(out_dir, "label_viz.png"))

		with open(os.path.join(out_dir, "label_names.txt"), "w") as f:
			for lbl_name in label_names:
				f.write(lbl_name + "\n")

		info = dict(label_names = label_names)
		with open(out_dir + '/info.yaml','w') as f:
			yaml.safe_dump(info, f, default_flow_style=False)
	

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值