Example #1
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('json_file')
    args = parser.parse_args()

    json_file = args.json_file

    data = json.load(open(json_file))

    img = utils.img_b64_to_arr(data['imageData'])

    label_name_to_value = {'_background_': 0}
    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

    lbl = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)

    captions = [
        '{}: {}'.format(lv, ln) for ln, lv in label_name_to_value.items()
    ]
    lbl_viz = utils.draw_label(lbl, img, captions)

    plt.subplot(121)
    plt.imshow(img)
    plt.subplot(122)
    plt.imshow(lbl_viz)
    plt.show()
Example #2
0
def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('json_file')
    parser.add_argument('-o', '--out', default=None)
    args = parser.parse_args()
    json_file = args.json_file
    list = os.listdir(json_file)
    for i in range(0, len(list)):
        path = os.path.join(json_file, list[i])
        if os.path.isfile(path):
            data = json.load(open(path))
            img = utils.img_b64_to_arr(data['imageData'])
            lbl, lbl_names = utils.labelme_shapes_to_label(
                img.shape, data['shapes'])
            captions = [
                '%d: %s' % (l, name) for l, name in enumerate(lbl_names)
            ]
            lbl_viz = utils.draw_label(lbl, img, captions)
            out_dir = osp.basename(list[i]).replace('.', '_')
            out_dir = osp.join(osp.dirname(list[i]), out_dir)
            if not osp.exists(out_dir):
                os.mkdir(out_dir)
            PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
            utils.lblsave(osp.join(out_dir, 'label.png'), lbl)
            PIL.Image.fromarray(lbl_viz).save(
                osp.join(out_dir, 'label_viz.png'))
            with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
                for lbl_name in lbl_names:
                    f.write(lbl_name + '\n')
            warnings.warn('info.yaml is being replaced by label_names.txt')
            info = dict(label_names=lbl_names)
            with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
                yaml.safe_dump(info, f, default_flow_style=False)
            print('Saved to: %s' % out_dir)
Example #3
0
def main():
    '''
    parser = argparse.ArgumentParser()
    parser.add_argument('json_file')
    args = parser.parse_args()
    '''


    json_file = '/Users/nainggolan/Documents/dataset/te/1.json'

    out_dir = osp.basename(json_file).replace('.', '_')
    out_dir = osp.join(osp.dirname(json_file), out_dir)
    os.mkdir(out_dir)

    data = json.load(open(json_file))

    img = utils.img_b64_to_array(data['imageData'])
    lbl, lbl_names = utils.labelme_shapes_to_label(img.shape, data['shapes'])

    lbl_viz = utils.draw_label(lbl, img, lbl_names)

    PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
    PIL.Image.fromarray(lbl).save(osp.join(out_dir, 'label.png'))
    PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))

    info = dict(label_names=lbl_names)

    with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
        yaml.safe_dump(info, f, default_flow_style=False)

    print('wrote data to %s' % out_dir)
Example #4
0
def main():
    '''

    parser = argparse.ArgumentParser()
    parser.add_argument()
    args = parser.parse_args()
    '''

    json_file = '/Users/nainggolan/Desktop/te/1.json'

    data = json.load(open(json_file))  # 加载json文件

    img = utils.img_b64_to_array(data['imageData'])  # 解析原图片数据
    lbl, lbl_names = utils.labelme_shapes_to_label(
        img.shape, data['shapes']
    )  # 解析'shapes'中的字段信息,解析出每个对象的mask与对应的label   lbl存储 mask,lbl_names 存储对应的label
    # lal 像素取值 0、1、2 其中0对应背景,1对应第一个对象,2对应第二个对象
    # 使用该方法取出每个对象的mask mask=[] mask.append((lbl==1).astype(np.uint8)) # 解析出像素值为1的对象,对应第一个对象 mask 为0、1组成的(0为背景,1为对象)
    # lbl_names  ['background','cat_1','cat_2']

    captions = ['%d: %s' % (l, name) for l, name in enumerate(lbl_names)]
    lbl_viz = utils.draw_label(lbl, img, captions)

    plt.subplot(121)
    plt.imshow(img)
    plt.subplot(122)
    plt.imshow(lbl_viz)
    plt.show()
Example #5
0
def main():
    logger.warning('This script is aimed to demonstrate how to convert the'
                   'JSON file to a single image dataset, and not to handle'
                   'multiple JSON files to generate a real-use dataset.')

    parser = argparse.ArgumentParser()
    parser.add_argument('json_file')
    parser.add_argument('-o', '--out', default=None)
    args = parser.parse_args()

    json_file = args.json_file

    if args.out is None:
        out_dir = osp.basename(json_file).replace('.', '_')
        out_dir = osp.join(osp.dirname(json_file), out_dir)
    else:
        out_dir = args.out
    if not osp.exists(out_dir):
        os.mkdir(out_dir)

    data = json.load(open(json_file))

    if data['imageData']:
        imageData = data['imageData']
    else:
        imagePath = os.path.join(os.path.dirname(json_file), 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}
    for shape in sorted(data['shapes'], key=lambda x: x['label']):
        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
    lbl = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)

    label_names = [None] * (max(label_name_to_value.values()) + 1)
    for name, value in label_name_to_value.items():
        label_names[value] = name
    lbl_viz = utils.draw_label(lbl, img, label_names)

    PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
    utils.lblsave(osp.join(out_dir, 'label.png'), lbl)
    PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))

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

    logger.warning('info.yaml is being replaced by label_names.txt')
    info = dict(label_names=label_names)
    with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
        yaml.safe_dump(info, f, default_flow_style=False)

    logger.info('Saved to: {}'.format(out_dir))
Example #6
0
def json2dataset(json_dirpath):
    json_file = json_dirpath
    data = json.load(open(json_file))

    if data['imageData']:
        imageData = data['imageData']
    else:
        imagePath = os.path.join(os.path.dirname(json_file), 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}
    for shape in sorted(data['shapes'], key=lambda x: x['label']):
        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
    lbl = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)

    label_names = [None] * (max(label_name_to_value.values()) + 1)
    for name, value in label_name_to_value.items():
        label_names[value] = name
    lbl_viz = utils.draw_label(lbl, img, label_names)
    return lbl
Example #7
0
def singleFile(filePath):
    if os.path.isfile(filePath) and filePath.endswith('.json'):
        data = json.load(open(filePath))
        img = lUtils.img_b64_to_arr(data['imageData'])
        lbl, lbl_names = lUtils.labelme_shapes_to_label(
            img.shape, data['shapes'])
        # lbl[lbl>0] = 255
        # print(lbl)

        captions = ['%d: %s' % (l, name) for l, name in enumerate(lbl_names)]
        lbl_viz = lUtils.draw_label(lbl, img, captions)
        out_dir = osp.basename(filePath).replace('.', '_')
        out_dir = osp.join(osp.dirname(filePath), out_dir)
        if not osp.exists(out_dir):
            os.mkdir(out_dir)
        PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
        PIL.Image.fromarray(lbl).save(osp.join(out_dir, 'label.png'))
        print(np.max(lbl))
        lbl = np.array(lbl, dtype=np.uint8)
        lbl[lbl > 0] = 255

        PIL.Image.fromarray(lbl).save(osp.join(out_dir, 'label_255.png'))
        PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))
        with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
            for lbl_name in lbl_names:
                f.write(lbl_name + '\n')
        warnings.warn('info.yaml is being replaced by label_names.txt')
        info = dict(label_names=lbl_names)
        with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
            yaml.safe_dump(info, f, default_flow_style=False)
        print('Saved to: %s' % out_dir)
Example #8
0
def main():
    logger.warning('This script is aimed to demonstrate how to convert the'
                   'JSON file to a single image dataset, and not to handle'
                   'multiple JSON files to generate a real-use dataset.')

    parser = argparse.ArgumentParser()
    parser.add_argument('json_file')
    parser.add_argument('-o', '--out', default=None)
    args = parser.parse_args()

    json_file = args.json_file

    if args.out is None:
        out_dir = osp.basename(json_file).replace('.', '_')
        out_dir = osp.join(osp.dirname(json_file), out_dir)
    else:
        out_dir = args.out
    if not osp.exists(out_dir):
        os.mkdir(out_dir)

    data = json.load(open(json_file))

    if data['imageData']:
        imageData = data['imageData']
    else:
        imagePath = os.path.join(os.path.dirname(json_file), 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}
    for shape in sorted(data['shapes'], key=lambda x: x['label']):
        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
    lbl = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)

    label_names = [None] * (max(label_name_to_value.values()) + 1)
    for name, value in label_name_to_value.items():
        label_names[value] = name
    lbl_viz = utils.draw_label(lbl, img, label_names)

    PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
    utils.lblsave(osp.join(out_dir, 'label.png'), lbl)
    PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))

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

    logger.warning('info.yaml is being replaced by label_names.txt')
    info = dict(label_names=label_names)
    with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
        yaml.safe_dump(info, f, default_flow_style=False)

    logger.info('Saved to: {}'.format(out_dir))
Example #9
0
def save_label_from_json(json_file, out_dir):
    data = json.load(open(json_file))

    if data['imageData']:
        imageData = data['imageData']
    else:
        imagePath = osp.join(osp.dirname(json_file), 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}
    for shape in sorted(data['shapes'], key=lambda x: x['label']):
        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
    lbl = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)

    label_names = [None] * (max(label_name_to_value.values()) + 1)
    for name, value in label_name_to_value.items():
        label_names[value] = name
    lbl_viz = utils.draw_label(lbl, img, label_names)

    utils.lblsave(osp.join(out_dir, 'label.png'), lbl)
    PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))

    with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
        for lbl_name in label_names:
            f.write(lbl_name + '\n')
Example #10
0
def changeToDataset(json_dir, out_dir=None):

    # parser = argparse.ArgumentParser()
    # parser.add_argument('json_file')
    # parser.add_argument('-o', '--out', default=None)
    # args = parser.parse_args()

    for fileName in os.listdir(json_dir):
        if re.match(".*[.]json$", fileName):
            json_file = osp.join(json_dir, fileName)
            print json_file

            if out_dir is None:
                out_dir = osp.join(osp.dirname(json_file), "output")
            # else:
            # print 'Existed out_dir = ',out_dir

            if not osp.exists(out_dir):
                os.mkdir(out_dir)

            out_dir_label = os.path.join(out_dir, 'label')
            if not osp.exists(out_dir_label):
                os.mkdir(out_dir_label)

            out_dir_viz = os.path.join(out_dir, 'viz')
            if not osp.exists(out_dir_viz):
                os.mkdir(out_dir_viz)

            print "out_dir_label = ", out_dir_label

            data = json.load(open(json_file))
            img = utils.img_b64_to_array(data['imageData'])
            lbl, lbl_names = utils.labelme_shapes_to_label(
                img.shape, data['shapes'])
            #print 0: background 1: sto
            # for l, name in enumerate(lbl_names):
            #     print '%d: %s' % (l, name)
            captions = [
                '%d: %s' % (l, name) for l, name in enumerate(lbl_names)
            ]
            lbl_viz = utils.draw_label(lbl, img, captions)

            #New Name
            NewName = fileName.split('.')[0]
            print osp.join(out_dir, NewName + '.png')
            # PIL.Image.fromarray(img).save(osp.join(out_dir,NewName+ '_img.png'))
            PIL.Image.fromarray(lbl).save(
                osp.join(out_dir_label, NewName + '.png'))
            PIL.Image.fromarray(lbl_viz).save(
                osp.join(out_dir_viz, NewName + '_label_viz.png'))

            with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
                for lbl_name in lbl_names:
                    f.write(lbl_name + '\n')

            # warnings.warn('info.yaml is being replaced by label_names.txt')
            info = dict(label_names=lbl_names)
            with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
                yaml.safe_dump(info, f, default_flow_style=False)
Example #11
0
def json2label(json_folder):
    json_list = glob.glob(os.path.join(json_folder, '*.json'))

    annotations_dir = os.path.join(json_folder, "annotations")
    josn2labels_dir = os.path.join(json_folder, "josn2labels")

    if not os.path.exists(annotations_dir):
        os.makedirs(annotations_dir)
    if not os.path.exists(josn2labels_dir):
        os.makedirs(josn2labels_dir)

    for json_file in json_list:
        temp_name = json_file.split(".")[0].split("/")[-1]

        out_dir = os.path.join(josn2labels_dir, temp_name)
        if not osp.exists(out_dir):
            os.mkdir(out_dir)

        data = json.load(open(json_file))

        if data['imageData']:
            imageData = data['imageData']
        else:
            imagePath = os.path.join(os.path.dirname(json_file),
                                     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, '1': 1, '2': 2, '3': 3}

        lbl = utils.shapes_to_label(img.shape, data['shapes'],
                                    label_name_to_value)

        label_names = [None] * (max(label_name_to_value.values()) + 1)
        for name, value in label_name_to_value.items():
            label_names[value] = name
        lbl_viz = utils.draw_label(lbl, img, label_names)

        PIL.Image.fromarray(img).save(
            osp.join(out_dir, '%s_img.png' % (temp_name)))
        utils.lblsave(osp.join(out_dir, '%s.png' % (temp_name)), lbl)
        utils.lblsave(osp.join(annotations_dir, '%s.png' % (temp_name)), lbl)
        PIL.Image.fromarray(lbl_viz).save(
            osp.join(out_dir, '%s_label_viz.png' % (temp_name)))

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

        warnings.warn('info.yaml is being replaced by label_names.txt')
        info = dict(label_names=label_names)
        with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
            yaml.safe_dump(info, f, default_flow_style=False)

        print('Saved to: %s' % out_dir)
def main():

    json_file = 'C:/Users/QJ/Desktop/hh/total'
    list = os.listdir(json_file)
    for i in range(0, len(list)):
        path = os.path.join(json_file, list[i])
        if os.path.isfile(path):
            data = json.load(open(path))
            img = utils.img_b64_to_array(data['imageData'])
            lbl, lbl_names = utils.labelme_shapes_to_label(
                img.shape, data['shapes'])

            captions = [
                '%d: %s' % (l, name) for l, name in enumerate(lbl_names)
            ]
            lbl_viz = utils.draw_label(lbl, img, captions)
            out_dir = osp.basename(list[i]).replace('.', '_')
            out_dir = osp.join(osp.dirname(list[i]), out_dir)
            out_dir = json_file + "/" + out_dir
            if not osp.exists(out_dir):
                os.mkdir(out_dir)

            PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
            # PIL.Image.fromarray(lbl).save()
            labelpath = osp.join(out_dir, 'label.png')
            # PIL.Image.fromarray(lbl).save(labelpath)
            # opencvimg16 = cv2.imread(labelpath)
            # opencvimg.convertTo(opencvimg6,)
            lbl8u = np.zeros((lbl.shape[0], lbl.shape[1]), dtype=np.uint8)
            for i in range(lbl.shape[0]):
                for j in range(lbl.shape[1]):
                    lbl8u[i, j] = lbl[i, j]
            PIL.Image.fromarray(lbl8u).save(labelpath)
            # Alllabelpath="%s"

        PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))

        with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
            for lbl_name in lbl_names:
                f.write(lbl_name + '\n')

        warnings.warn('info.yaml is being replaced by label_names.txt')
        info = dict(label_names=lbl_names)
        with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
            yaml.dump(info, f, default_flow_style=False)

        fov = open(osp.join(out_dir, 'info.yaml'), 'w')
        for key in info:
            fov.writelines(key)
            fov.write(':\n')
        for k, v in lbl_names.items():
            fov.write('  ')
            fov.write(k)
            fov.write(':\n')

        fov.close()
        print('Saved to: %s' % out_dir)
Example #13
0
def main():
    logger.warning('This script is aimed to demonstrate how to convert the'
                   'JSON file to a single image dataset, and not to handle'
                   'multiple JSON files to generate a real-use dataset.')

    # parser = argparse.ArgumentParser()
    # parser.add_argument('json_file')
    # parser.add_argument('-o', '--out', default=None)
    # args = parser.parse_args()

    json_files = glob.glob(r'C:\Users\Zeran\Desktop\loudi\*.json')
    for json_file in json_files:

        out_dir = osp.basename(json_file).replace('.', '_')
        out_dir = osp.join(osp.dirname(json_file), out_dir)

        # reload(sys)
        # sys.setdefaultencoding('utf8')
        f = open(json_file, encoding='utf-8')
        text = f.read()
        # text = text.decode("gbk").encode("utf-8")
        data = json.loads(text)

        # data = f.read().decode(encoding='gbk').encode(encoding='utf-8')

        # data = json.load(open(json_file))

        if data['imageData']:
            imageData = data['imageData']
        else:
            imagePath = os.path.join(os.path.dirname(json_file),
                                     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}
        for shape in sorted(data['shapes'], key=lambda x: x['label']):
            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] = 255
        lbl = utils.shapes_to_label(img.shape, data['shapes'],
                                    label_name_to_value)

        label_names = [None] * (max(label_name_to_value.values()) + 1)
        for name, value in label_name_to_value.items():
            label_names[value] = name
        lbl_viz = utils.draw_label(lbl, img, label_names)
        saved_name = os.path.splitext(os.path.basename(json_file))[0] + '.png'
        utils.lblsave(
            osp.join('D:\\coslight\\0304_beforetolabel\\label\\', saved_name),
            lbl)
Example #14
0
def changeToDataset(json_dir,out_dir=None):


    # parser = argparse.ArgumentParser()
    # parser.add_argument('json_file')
    # parser.add_argument('-o', '--out', default=None)
    # args = parser.parse_args()


    for fileName in os.listdir(json_dir):
        if re.match(".*[.]json$",fileName):
            json_file = osp.join(json_dir,fileName)
            print json_file

            if out_dir is None:
                out_dir = osp.join(osp.dirname(json_file), "output")
            # else:
                # print 'Existed out_dir = ',out_dir

            if not osp.exists(out_dir):
                os.mkdir(out_dir)

            out_dir_label = os.path.join(out_dir, 'label')
            if not osp.exists(out_dir_label):
                os.mkdir(out_dir_label)

            out_dir_viz = os.path.join(out_dir,'viz')
            if not osp.exists(out_dir_viz):
                os.mkdir(out_dir_viz)

            print "out_dir_label = ",out_dir_label

            data = json.load(open(json_file))
            img = utils.img_b64_to_array(data['imageData'])
            lbl, lbl_names = utils.labelme_shapes_to_label(img.shape, data['shapes'])
            #print 0: background 1: sto
            # for l, name in enumerate(lbl_names):
            #     print '%d: %s' % (l, name)
            captions = ['%d: %s' % (l, name) for l, name in enumerate(lbl_names)]
            lbl_viz = utils.draw_label(lbl, img, captions)

            #New Name
            NewName = fileName.split('.')[0]
            print osp.join(out_dir,NewName+ '.png')
            # PIL.Image.fromarray(img).save(osp.join(out_dir,NewName+ '_img.png'))
            PIL.Image.fromarray(lbl).save(osp.join(out_dir_label, NewName+ '.png'))
            PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir_viz, NewName+ '_label_viz.png'))

            with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
                for lbl_name in lbl_names:
                    f.write(lbl_name + '\n')

            # warnings.warn('info.yaml is being replaced by label_names.txt')
            info = dict(label_names=lbl_names)
            with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
                yaml.safe_dump(info, f, default_flow_style=False)
Example #15
0
def main():
    count = os.listdir("./before/")
    for i in range(0, len(count)):
        path = os.path.join("./before", count[i])
        if os.path.isfile(path) and path.endswith('json'):
            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}
            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 must be dense
            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)
            captions = [
                '{}: {}'.format(lv, ln)
                for ln, lv in label_name_to_value.items()
            ]
            lbl_viz = utils.draw_label(lbl, img, captions)
            out_dir = osp.basename(count[i]).replace('.', '_')
            out_dir = osp.join(osp.dirname(count[i]), out_dir)
            out_dir = osp.join("output", out_dir)
            if not osp.exists(out_dir):
                #os.mkdir(out_dir)
                os.makedirs(out_dir)
            PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
            utils.lblsave(osp.join(out_dir, 'label.png'), lbl)
            PIL.Image.fromarray(lbl_viz).save(
                osp.join(out_dir, 'label_viz.png'))
            with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
                for lbl_name in label_names:
                    f.write(lbl_name + '\n')
            warnings.warn('info.yaml is being replaced by label_names.txt')
            info = dict(label_names=label_names)
            with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
                yaml.safe_dump(info, f, default_flow_style=False)
            print('Saved to: %s' % out_dir)
Example #16
0
def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('label_png', help='label PNG file')
    args = parser.parse_args()

    lbl = np.asarray(PIL.Image.open(args.label_png))

    logger.info('label shape: {}'.format(lbl.shape))
    logger.info('unique label values: {}'.format(np.unique(lbl)))

    lbl_viz = utils.draw_label(lbl)
    plt.imshow(lbl_viz)
    plt.show()
def main():
    warnings.warn("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 = argparse.ArgumentParser()
    parser.add_argument('json_file')
    parser.add_argument('-o', '--out', default=None)
    args = parser.parse_args()
    json_file = args.json_file
    print("json_flie= ",json_file)
    if args.out is None:
        out_dir = osp.basename(json_file).replace('.', '_')
        out_dir = osp.join(osp.dirname(json_file), out_dir)
    else:
        out_dir = args.out
    if not osp.exists(out_dir):
        os.mkdir(out_dir)
    data = json.load(open(json_file))
    print("json---load")
    img = utils.img_b64_to_arr(data['imageData'])
    label_name_to_value = {'_background_': 0}
    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 must be dense
    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)
    captions = ['{}: {}'.format(lv, ln)
                for ln, lv in label_name_to_value.items()]
    lbl_viz = utils.draw_label(lbl, img, captions)
    PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
    PIL.Image.fromarray(lbl).save(osp.join(out_dir, 'label.png'))
    PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))
    with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
        for lbl_name in label_names:
            f.write(lbl_name + '\n')
    warnings.warn('info.yaml is being replaced by label_names.txt')
    info = dict(label_names=label_names)
    with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
        yaml.safe_dump(info, f, default_flow_style=False)
    print('Saved to: %s' % out_dir)
Example #18
0
def json_to_dataset(json_file_path):
    out_dir = osp.basename(json_file_path).replace('.', '_')
    out_dir = osp.join(osp.dirname(json_file_path), out_dir)
    if not osp.exists(out_dir): os.mkdir(out_dir)
    data = json.load(open(json_file_path))
    img = utils.img_b64_to_array(data['imageData'])
    lbl, lbl_names = utils.labelme_shapes_to_label(img.shape, data['shapes'])
    lbl_viz = utils.draw_label(lbl, img, lbl_names)
    PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
    PIL.Image.fromarray(lbl).save(osp.join(out_dir, 'label.png'))
    PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))
    info = dict(label_names=lbl_names)
    with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
        yaml.safe_dump(info, f, default_flow_style=False)
    print('wrote data to %s' % out_dir)
Example #19
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('json_file')
    args = parser.parse_args()

    json_file = args.json_file

    data = json.load(open(json_file))

    img = utils.img_b64_to_array(data['imageData'])
    lbl, lbl_names = utils.labelme_shapes_to_label(img.shape, data['shapes'])

    captions = ['%d: %s' % (l, name) for l, name in enumerate(lbl_names)]
    lbl_viz = utils.draw_label(lbl, img, captions)

    # lbl_names[0] 默认为背景,对应的像素值为0
    # 解析图片中的对象 像素值不为0(0 对应背景)
    mask = []
    class_id = []
    for i in range(1, len(lbl_names)):  # 跳过第一个class(默认为背景)
        mask.append((lbl == i).astype(
            np.uint8))  # 解析出像素值为1的对应,对应第一个对象 mask 为0、1组成的(0为背景,1为对象)
        class_id.append(i)  # mask与clas 一一对应

    mask = np.transpose(np.asarray(mask, np.uint8),
                        [1, 2, 0])  # 转成[h,w,instance count]
    class_id = np.asarray(class_id, np.uint8)  # [instance count,]
    class_name = lbl_names[1:]  # 不需要包含背景 lbl_names[0] 默认为背景

    plt.subplot(221)
    plt.imshow(img)
    plt.axis('off')

    plt.subplot(222)
    plt.imshow(lbl_viz)
    plt.axis('off')

    plt.subplot(223)
    plt.imshow(mask[:, :, 0], 'gray')
    plt.title(class_name[0] + '\n id ' + str(class_id[0]))
    plt.axis('off')

    plt.subplot(224)
    plt.imshow(mask[:, :, 1], 'gray')
    plt.title(class_name[1] + '\n id ' + str(class_id[1]))
    plt.axis('off')

    plt.show()
Example #20
0
def main():
    logger = logging.Logger('labelme')
    logger.setLevel(logging.INFO)

    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('label_png', help='label PNG file')
    args = parser.parse_args()

    lbl = np.asarray(PIL.Image.open(args.label_png))

    logger.info('label shape: {}'.format(lbl.shape))
    logger.info('unique label values: {}'.format(np.unique(lbl)))

    lbl_viz = utils.draw_label(lbl)
    plt.imshow(lbl_viz)
    plt.show()
def main():
    # parser = argparse.ArgumentParser()
    # parser.add_argument('json_file')
    # args = parser.parse_args()
    #
    # json_file = args.json_file
    # json_file=r"C:\Users\Administrator\Desktop\windows_v1.5.1\data\WIN_20180504_10_05_03_Pro.json"
    json_file = r"C:\Users\Administrator\Desktop\windows_v1.5.1\data\img00000001.json"

    data = json.load(open(json_file))

    img = utils.img_b64_to_array(data['imageData'])
    lbl, lbl_names = utils.labelme_shapes_to_label(img.shape, data['shapes'])

    lbl_viz = utils.draw_label(lbl, img, lbl_names)

    plt.imshow(lbl_viz)
    plt.show()
Example #22
0
def main():
    warnings.warn("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 = argparse.ArgumentParser()
    parser.add_argument('json_file')
    parser.add_argument('-o', '--out', default=None)
    args = parser.parse_args()

    json_file = args.json_file

    if args.out is None:
        out_dir = osp.basename(json_file).replace('.', '_')
        out_dir = osp.join(osp.dirname(json_file), out_dir)
    else:
        out_dir = args.out
    if not osp.exists(out_dir):
        os.mkdir(out_dir)

    data = json.load(open(json_file))

    img = utils.img_b64_to_array(data['imageData'])
    lbl, lbl_names = utils.labelme_shapes_to_label(img.shape, data['shapes'])

    captions = ['%d: %s' % (l, name) for l, name in enumerate(lbl_names)]
    lbl_viz = utils.draw_label(lbl, img, captions)

    PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
    PIL.Image.fromarray(lbl).save(osp.join(out_dir, 'label.png'))
    PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))

    with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
        for lbl_name in lbl_names:
            f.write(lbl_name + '\n')

    warnings.warn('info.yaml is being replaced by label_names.txt')
    info = dict(label_names=lbl_names)
    with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
        yaml.safe_dump(info, f, default_flow_style=False)

    print('Saved to: %s' % out_dir)
Example #23
0
def main():
    warnings.warn("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 = argparse.ArgumentParser()
    parser.add_argument('json_file')
    parser.add_argument('-o', '--out', default=None)
    args = parser.parse_args()

    json_file = args.json_file

    if args.out is None:
        out_dir = osp.basename(json_file).replace('.', '_')
        out_dir = osp.join(osp.dirname(json_file), out_dir)
    else:
        out_dir = args.out
    if not osp.exists(out_dir):
        os.mkdir(out_dir)

    data = json.load(open(json_file))

    img = utils.img_b64_to_array(data['imageData'])
    lbl, lbl_names = utils.labelme_shapes_to_label(img.shape, data['shapes'])

    captions = ['%d: %s' % (l, name) for l, name in enumerate(lbl_names)]
    lbl_viz = utils.draw_label(lbl, img, captions)

    PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
    PIL.Image.fromarray(lbl).save(osp.join(out_dir, 'label.png'))
    PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))

    with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
        for lbl_name in lbl_names:
            f.write(lbl_name + '\n')

    warnings.warn('info.yaml is being replaced by label_names.txt')
    info = dict(label_names=lbl_names)
    with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
        yaml.safe_dump(info, f, default_flow_style=False)

    print('Saved to: %s' % out_dir)
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('json_file')
    args = parser.parse_args()

    json_file = args.json_file

    data = json.load(open(json_file))

    img = utils.img_b64_to_array(data['imageData'])
    lbl, lbl_names = utils.labelme_shapes_to_label(img.shape, data['shapes'])

    captions = ['%d: %s' % (l, name) for l, name in enumerate(lbl_names)]
    lbl_viz = utils.draw_label(lbl, img, captions)

    plt.subplot(121)
    plt.imshow(img)
    plt.subplot(122)
    plt.imshow(lbl_viz)
    plt.show()
Example #25
0
def writeimages(img, lbl, depth_map, jsonFile, sufix, out_images_dir,
                out_labels_dir, out_labels_raw_dir, debug_dir,
                label_name_to_value, args):
    #Plot visualization if in debug mode
    if args.debug:
        label_names = [None] * (max(label_name_to_value.values()) + 1)
        for name, value in label_name_to_value.items():
            label_names[value] = name
        lbl_viz = utils.draw_label(lbl, img, label_names)
        PIL.Image.fromarray(lbl_viz).save(
            osp.join(
                debug_dir,
                jsonFile.replace('./', '').replace('../', '').replace(
                    '/', '_').replace('.json',
                                      '-' + sufix + '-label_viz.png')))

    jsonFileName = jsonFile[jsonFile.rfind('/') + 1:]

    #Save image
    if out_images_dir is not None:
        PIL.Image.fromarray(img).save(
            osp.join(out_images_dir, jsonFileName.replace('.json', '.jpg')))
    #Save labels
    utils.lblsave(
        osp.join(out_labels_dir,
                 jsonFileName.replace('.json', '-' + sufix + '-label.png')),
        lbl)
    #Save labels with raw annotation
    PIL.Image.fromarray(lbl.astype(dtype=np.uint8)).save(
        osp.join(out_labels_raw_dir,
                 jsonFileName.replace('.json',
                                      '-' + sufix + '-label_raw.png')))
    if args.depth:
        #Save depth image
        #        PIL.Image.fromarray(depth_map.astype(dtype=np.uint8)).save(
        #            osp.join(out_images_dir, jsonFile.replace('.json','-depth.png'))
        #        )
        PIL.Image.fromarray(depth_map.astype(dtype=np.uint8)).save(
            osp.join(out_images_dir,
                     jsonFileName.replace('.json',
                                          '-' + sufix + '-depth.png')))
Example #26
0
def main():
    logger = logging.Logger('labelme')
    logger.setLevel(logging.INFO)

    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('label_png', help='label PNG file')
    args = parser.parse_args()

    lbl = np.asarray(PIL.Image.open(args.label_png))
    if lbl.dtype != np.int32:
        logger.warn(
            'We recomment numpy.int32 for the label, but it has: {}'.format(
                lbl.dtype))

    logger.info('label shape: {}'.format(lbl.shape))
    logger.info('unique label values: {}'.format(np.unique(lbl)))

    lbl_viz = utils.draw_label(lbl)
    plt.imshow(lbl_viz)
    plt.show()
Example #27
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('json_file')
    args = parser.parse_args()

    json_file = args.json_file

    data = json.load(open(json_file))

    if data['imageData']:
        imageData = data['imageData']
    else:
        imagePath = os.path.join(os.path.dirname(json_file), 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}
    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

    lbl = utils.shapes_to_label(
        img.shape, data['shapes'], label_name_to_value)

    captions = ['{}: {}'.format(lv, ln)
                for ln, lv in label_name_to_value.items()]
    lbl_viz = utils.draw_label(lbl, img, captions)

    plt.subplot(121)
    plt.imshow(img)
    plt.subplot(122)
    plt.imshow(lbl_viz)
    plt.show()
Example #28
0
def get_all_class_mask(json_file_path):
    '''
    returns:  
    img: 原图  
    mask: 所有类别的mask,二值图,0和255  
    img_with_label: 带掩模的图  
    lbl_value_to_names: mask的index可以从lbl_value_to_names得到class名称  
    '''
    if os.path.exists(json_file_path):
        with open(json_file_path) as json_f:
            data = json.load(json_f)
            img = utils.img_b64_to_arr(data['imageData'])
            #lbl是一个mask,每个obj的像素赋值为该obj对应的value
            lbl, lbl_names_to_value = utils.labelme_shapes_to_label(
                img.shape, data['shapes'])  #包含背景0
            captions = [
                '%d: %s' % (l, name)
                for l, name in enumerate(lbl_names_to_value)
            ]
            img_with_label = utils.draw_label(lbl, img, captions)

            tmp = [(l - 1, name) for l, name in enumerate(lbl_names_to_value)
                   if l != 0]
            lbl_value_to_names = {}
            for l, name in tmp:
                lbl_value_to_names[l] = name  #不包含背景

            mask = []
            # instance_id=[]
            for i in range(1, len(lbl_names_to_value)):  # 跳过第一个class(默认为背景)
                mask.append(
                    (lbl == i).astype(np.uint8) * 255
                )  # mask[i]对应第i个对象的mask, 为0、255组成的(0为背景,255为对象),所有对象的mask叠起来组成三维
                # instance_id.append(i) # mask与clas 一一对应
            # all_mask=np.transpose(np.asarray(mask,np.uint8),[1,2,0]) # 转成[h,w,instance count]
            # instance_id=np.asarray(instance_id,np.uint8) # [instance count,]
    else:
        raise Exception("no such a json file!!")

    return img, mask, img_with_label, lbl_value_to_names
Example #29
0
def save_label_info(img, name, dir_label, dir_info, dir_vis, shape_):
    label_name_to_value = {'_background_': 0, "1": 1, "2": 2, "3": 3}
    # for shape in 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
    # print(label_name_to_value.items())
    label_values, label_names = [], []
    for ln, lv in sorted(label_name_to_value.items(), key=lambda x: x[1]):
        # print(ln,lv)
        label_values.append(lv)
        label_names.append(ln)
    assert label_values == list(range(len(label_values)))

    lbl = utils.shapes_to_label(img.shape, shape_,
                                label_name_to_value)  # 'instance'
    # print(ins)

    captions = [
        '{}: {}'.format(lv, ln) for ln, lv in label_name_to_value.items()
    ]
    lbl_viz = utils.draw_label(lbl, img, captions)

    # ins_viz=utils.draw_label(lbl, img, captions)
    # PIL.Image.fromarray(img).save('img.png')
    # PIL.Image.fromarray(lbl).save(osp.join(out_dir, 'label.png'))
    utils.lblsave(dir_label + name + '.png', lbl)
    PIL.Image.fromarray(lbl_viz).save(dir_vis + name + '.png')

    # with open('label_names.txt', 'w') as f:
    #     for lbl_name in label_names:
    #         f.write(lbl_name + '\n')

    # warnings.warn('info.yaml is being replaced by label_names.txt')
    info = dict(label_names=label_names)
    with open(dir_info + name + '.yaml', 'w') as f:
        yaml.safe_dump(info, f, default_flow_style=False)
Example #30
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('json_file')
    args = parser.parse_args()

    json_file = args.json_file

    data = json.load(open(json_file))

    if data['imageData']:
        imageData = data['imageData']
    else:
        imagePath = os.path.join(os.path.dirname(json_file), 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}
    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

    lbl = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)

    captions = [
        '{}: {}'.format(lv, ln) for ln, lv in label_name_to_value.items()
    ]
    lbl_viz = utils.draw_label(lbl, img, captions)

    plt.subplot(121)
    plt.imshow(img)
    plt.subplot(122)
    plt.imshow(lbl_viz)
    plt.show()
Example #31
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('json_file')
    args = parser.parse_args()

    json_file = args.json_file
    #json_file = "D:/0test/1.json"
    #pdb.set_trace()
    data = json.load(open(json_file))

    if data['imageData']:
        imageData = data['imageData']
    else:
        imagePath = os.path.join(os.path.dirname(json_file), 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}
    for shape in sorted(data['shapes'], key=lambda x: x['label']):
        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
    lbl = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)

    label_names = [None] * (max(label_name_to_value.values()) + 1)
    for name, value in label_name_to_value.items():
        label_names[value] = name
    lbl_viz = utils.draw_label(lbl, img, label_names)

    plt.subplot(121)
    plt.imshow(img)
    plt.subplot(122)
    plt.imshow(lbl_viz)
    plt.show()
Example #32
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('json_file')
    args = parser.parse_args()

    json_file = args.json_file

    data = json.load(open(json_file))

    if data['imageData']:
        imageData = data['imageData']
    else:
        imagePath = os.path.join(os.path.dirname(json_file), 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}
    for shape in sorted(data['shapes'], key=lambda x: x['label']):
        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
    lbl = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)

    label_names = [None] * (max(label_name_to_value.values()) + 1)
    for name, value in label_name_to_value.items():
        label_names[value] = name
    lbl_viz = utils.draw_label(lbl, img, label_names)

    plt.subplot(121)
    plt.imshow(img)
    plt.subplot(122)
    plt.imshow(lbl_viz)
    plt.show()
Example #33
0
def handle_json(json_file, out_dir):
    data = json.load(open(json_file))
    img = utils.img_b64_to_arr(data['imageData'])
    label_name_to_value = {'_background_': 0}
    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 must be dense
    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)

    captions = [
        '{}: {}'.format(lv, ln) for ln, lv in label_name_to_value.items()
    ]
    lbl_viz = utils.draw_label(lbl, img, captions)

    PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
    PIL.Image.fromarray(lbl).save(osp.join(out_dir, 'label.png'))
    PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))

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

    # print('\n  info.yaml is being replaced by label_names.txt')
    info = dict(label_names=label_names)
    with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
        yaml.safe_dump(info, f, default_flow_style=False)
Example #34
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('json_file')
    args = parser.parse_args()

    json_file = args.json_file

    data = json.load(open(json_file))

    if data['imageData']:
        imageData = data['imageData']
    else:
        imagePath = os.path.join(os.path.dirname(json_file), 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)

    lbl, label_name_to_value = utils.shapes_to_label(img.shape, data['shapes'])

    lbl = utils.shapes_to_label(
        img.shape,
        shapes=data['shapes'],
        label_name_to_value=label_name_to_value,
    )

    label_names = [None] * (max(label_name_to_value.values()) + 1)
    for name, value in label_name_to_value.items():
        label_names[value] = name
    lbl_viz = utils.draw_label(lbl, img, label_names)

    plt.subplot(121)
    plt.imshow(img)
    plt.subplot(122)
    plt.imshow(lbl_viz)
    plt.show()
Example #35
0
def main():
    warnings.warn("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 = argparse.ArgumentParser()
    parser.add_argument('json_file')
    parser.add_argument('-o', '--out', default=None)
    args = parser.parse_args()

    json_file = args.json_file

    #freedom
    list_path = os.listdir(json_file)
    print('freedom =', json_file)
    for i in range(0, len(list_path)):
        path = os.path.join(json_file, list_path[i])
        if os.path.isfile(path):

            data = json.load(open(path))
            img = utils.img_b64_to_arr(data['imageData'])
            lbl, lbl_names = utils.labelme_shapes_to_label(
                img.shape, data['shapes'])

            captions = [
                '%d: %s' % (l, name) for l, name in enumerate(lbl_names)
            ]

            lbl_viz = utils.draw_label(lbl, img, captions)
            out_dir = osp.basename(path).replace('.', '_')
            save_file_name = out_dir
            out_dir = osp.join(osp.dirname(path), out_dir)

            if not osp.exists(json_file + '\\' + 'labelme_json'):
                os.mkdir(json_file + '\\' + 'labelme_json')
            labelme_json = json_file + '\\' + 'labelme_json'

            out_dir1 = labelme_json + '\\' + save_file_name
            if not osp.exists(out_dir1):
                os.mkdir(out_dir1)

            PIL.Image.fromarray(img).save(out_dir1 + '\\' + save_file_name +
                                          '_img.png')
            PIL.Image.fromarray(lbl).save(out_dir1 + '\\' + save_file_name +
                                          '_label.png')

            PIL.Image.fromarray(lbl_viz).save(out_dir1 + '\\' +
                                              save_file_name +
                                              '_label_viz.png')

            if not osp.exists(json_file + '\\' + 'mask_png'):
                os.mkdir(json_file + '\\' + 'mask_png')
            mask_save2png_path = json_file + '\\' + 'mask_png'
            ################################
            #mask_pic = cv2.imread(out_dir1+'\\'+save_file_name+'_label.png',)
            #print('pic1_deep:',mask_pic.dtype)

            mask_dst = img_as_ubyte(lbl)  #mask_pic
            print('pic2_deep:', mask_dst.dtype)
            cv2.imwrite(
                mask_save2png_path + '\\' + save_file_name + '_label.png',
                mask_dst)
            ##################################

            with open(osp.join(out_dir1, 'label_names.txt'), 'w') as f:
                for lbl_name in lbl_names:
                    f.write(lbl_name + '\n')

            warnings.warn('info.yaml is being replaced by label_names.txt')
            info = dict(label_names=lbl_names)
            with open(osp.join(out_dir1, 'info.yaml'), 'w') as f:
                yaml.safe_dump(info, f, default_flow_style=False)

            print('Saved to: %s' % out_dir1)
Example #36
0
def main():
    warnings.warn("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 = argparse.ArgumentParser()
    parser.add_argument('json_file')
    parser.add_argument('-o', '--out', default=None)
    args = parser.parse_args()

    json_file = args.json_file

    if args.out is None:
        out_dir = osp.basename(json_file).replace('.', '_')
        out_dir = osp.join(osp.dirname(json_file), out_dir)
    else:
        out_dir = args.out
    if not osp.exists(out_dir):
        os.mkdir(out_dir)

    data = json.load(open(json_file))

    if data['imageData']:
        imageData = data['imageData']
    else:
        imagePath = os.path.join(os.path.dirname(json_file), 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}
    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 must be dense
    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)

    captions = ['{}: {}'.format(lv, ln)
                for ln, lv in label_name_to_value.items()]
    lbl_viz = utils.draw_label(lbl, img, captions)

    PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
    PIL.Image.fromarray(lbl).save(osp.join(out_dir, 'label.png'))
    PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))

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

    warnings.warn('info.yaml is being replaced by label_names.txt')
    info = dict(label_names=label_names)
    with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
        yaml.safe_dump(info, f, default_flow_style=False)

    print('Saved to: %s' % out_dir)
Example #37
0
def main():
    print('This script is aimed to demonstrate how to convert the'
          'JSON file to a single image dataset, and not to handle'
          'multiple JSON files to generate a real-use dataset.')

    path_file_name = glob.glob('*.json')
    file_num = len(path_file_name)
    print('INFO:There are ' + str(file_num) + ' json files')
    file_name = [i for i in range(file_num)]
    for i in range(file_num):
        file_name[i] = path_file_name[i].split('\\')[-1]
        print('INFO:' + file_name[i] + ' is dealt')
        data = json.load(open(path_file_name[i]))
        imageData = data.get('imageData')

        out_dir = osp.basename(path_file_name[i]).replace('.', '_')
        out_dir = osp.join(osp.dirname(path_file_name[i]), out_dir)
        if not os.path.exists(out_dir):
            os.mkdir(out_dir)

        if not imageData:
            imagePath = os.path.join(os.path.dirname(path_file_name[i]),
                                     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}
        for shape in sorted(data['shapes'], key=lambda x: x['label']):
            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
        lbl = utils.shapes_to_label(img.shape, data['shapes'],
                                    label_name_to_value)

        label_names = [None] * (max(label_name_to_value.values()) + 1)
        for name, value in label_name_to_value.items():
            label_names[value] = name
        lbl_viz = utils.draw_label(lbl, img, label_names)

        PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
        utils.lblsave(osp.join(out_dir, 'label.png'), lbl)
        PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))

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

        print('INFO:info.yaml is being replaced by label_names.txt')
        info = dict(label_names=label_names)
        with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
            yaml.safe_dump(info, f, default_flow_style=False)

        print('INFO:Saved to: {}'.format('images/segmentation/test/' +
                                         file_name[i]))

    print('INFO:finished!')