import argparse
import json
import os
import os
import PIL.Image
import yaml
from labelme import utils
import base64
import numpy as np
import cv2 as cv
from skimage import img_as_ubyte
def parse_arguments():
parser = argparse.ArgumentParser(description="This script is aimed to demonstrate how to convert the\n"
"JSON file to a single image dataset, and not to handle\n"
"multiple JSON files to generate a real-use dataset.")
parser.add_argument("--input_path", type=str,default='segmentation')
parser.add_argument("--output_path", type=str,default='seg2_mask')
return parser.parse_args()
def main():
args = parse_arguments()
target = args.output_path
if not os.path.exists(target):
os.mkdir(target)
if not os.path.exists(target+'/img/'):
os.mkdir(target+'/img/')
if not os.path.exists(target+'/label/'):
os.mkdir(target+'/label/' )
json_file = args.input_path
count = [e for e in os.listdir(json_file) if e.endswith('.json')]
for i in range(0, len(count)):
path = os.path.join(json_file, count[i])
name = count[i].split('.')[0]
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_b64decode = base64.b64decode(imageData)
img_array = np.frombuffer(img_b64decode, np.uint8)
img = cv.imdecode(img_array, cv.COLOR_BGR2RGB)
mask = np.zeros_like(img, dtype=np.uint8)
if len(data["shapes"])<2:
print(count[i])
continue
if data["shapes"][0]['label'] == 'pupil':
points = data["shapes"][1]["points"]
points = np.array(points, dtype=np.int32)
cv.fillPoly(mask, [points], (255, 255, 255))
points = data["shapes"][0]["points"]
points = np.array(points, dtype=np.int32)
cv.fillPoly(mask, [points], (0, 0, 0))
else:
points = data["shapes"][0]["points"]
points = np.array(points, dtype=np.int32)
cv.fillPoly(mask, [points], (255, 255, 255))
points = data["shapes"][1]["points"]
points = np.array(points, dtype=np.int32)
cv.fillPoly(mask, [points], (0, 0, 0))
cv.imwrite('%s/img/%s.png' % (target, name), img)
cv.imwrite('%s/label/%s.png' % (target, name), mask)
if __name__ == '__main__':
main()