Beispiel #1
0
    def debug_render(self, T_camera2world):
        class_names = self._models.class_names

        height, width = 480, 640
        fovx = 60
        fovy = fovx / width * height

        scene = morefusion.extra.pybullet.get_trimesh_scene()
        list(scene.geometry.values())[0].visual.face_colors = (1.0, 1.0, 1.0)
        for name, geometry in scene.geometry.items():
            if hasattr(geometry.visual, "to_color"):
                geometry.visual = geometry.visual.to_color()
        scene.camera.resolution = (width, height)
        scene.camera.fov = (fovx, fovy)
        scene.camera_transform = morefusion.extra.trimesh.to_opengl_transform(
            T_camera2world)

        rgb, depth, ins, cls = self.render(
            T_camera2world,
            fovy=scene.camera.fov[1],
            height=height,
            width=width,
        )

        ins_viz = imgviz.label2rgb(ins + 1, rgb)
        cls_viz = imgviz.label2rgb(cls,
                                   rgb,
                                   label_names=class_names,
                                   font_size=20)
        viz = imgviz.tile([rgb, ins_viz, cls_viz],
                          border=(255, 255, 255),
                          shape=(1, 3))
        viz = imgviz.resize(viz, width=1500)
        imgviz.io.pyglet_imshow(viz, "pybullet")

        rgb = morefusion.extra.trimesh.save_image(scene)[:, :, :3]
        ins_viz = imgviz.label2rgb(ins + 1, rgb)
        cls_viz = imgviz.label2rgb(cls,
                                   rgb,
                                   label_names=class_names,
                                   font_size=20)
        viz = imgviz.tile([rgb, ins_viz, cls_viz],
                          border=(255, 255, 255),
                          shape=(1, 3))
        viz = imgviz.resize(viz, width=1500)
        imgviz.io.pyglet_imshow(viz, "trimesh")

        imgviz.io.pyglet_run()
Beispiel #2
0
    def output(self, ordered_keys=None):
        """
        Arguments:
            ordered_keys(list(str))
        """
        for filename in tqdm(glob.glob(osp.join(self.input_dir, "*.json"))):
            # print("Generating dataset from:", filename)

            label_file = labelme.LabelFile(filename=filename)

            base = osp.splitext(osp.basename(filename))[0]
            out_img_file = osp.join(self.output_dir, "JPEGImages",
                                    base + ".jpg")
            out_lbl_file = osp.join(self.output_dir, "SegmentationClass",
                                    base + ".npy")
            out_png_file = osp.join(self.output_dir, "SegmentationClassPNG",
                                    base + ".png")
            if not self.noviz:
                out_viz_file = osp.join(
                    self.output_dir,
                    "SegmentationClassVisualization",
                    base + ".jpg",
                )

            with open(out_img_file, "wb") as f:
                f.write(label_file.imageData)
            img = labelme.utils.img_data_to_arr(label_file.imageData)
            if ordered_keys is not None:
                newshapes = []
                for ok in ordered_keys:
                    for shape in label_file.shapes:
                        if shape["label"] == ok:
                            newshapes.append(shape)
                label_file.shapes = newshapes

            if self.debug:
                print(label_file.shapes)
                break

            lbl, _ = labelme.utils.shapes_to_label(
                img_shape=img.shape,
                shapes=label_file.shapes,
                label_name_to_value=self.class_name_to_id,
            )
            labelme.utils.lblsave(out_png_file, lbl)

            # np.save(out_lbl_file, lbl)

            if not self.noviz:
                if img.shape[0] == 1:  # gray img
                    img = imgviz.rgb2gray(img)
                viz = imgviz.label2rgb(
                    label=lbl,
                    # img=imgviz.rgb2gray(img),
                    img=img,
                    font_size=15,
                    label_names=self.class_names,
                    loc="rb",
                )
                imgviz.io.imsave(out_viz_file, viz)
def main():
    logger.warning('This script is aimed to demonstrate how to convert the '
                   'JSON file to a single image dataset.')
    logger.warning("It won't 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))
    imageData = data.get('imageData')

    if not imageData:
        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 = imgviz.label2rgb(
        label=lbl, img=imgviz.asgray(img), label_names=label_names, loc='rb'
    )

    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.info('Saved to: {}'.format(out_dir))
Beispiel #4
0
def main():
    logger.warning("This script is aimed to demonstrate how to convert the "
                   "JSON file to a single image dataset.")
    logger.warning("It won't 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))
    imageData = data.get("imageData")

    if not imageData:
        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 = imgviz.label2rgb(label=lbl,
                               img=imgviz.asgray(img),
                               label_names=label_names,
                               loc="rb")

    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.info("Saved to: {}".format(out_dir))
Beispiel #5
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(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 = imgviz.label2rgb(label=lbl,
                                   img=imgviz.asgray(img),
                                   label_names=label_names,
                                   loc='rb')

        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:Saved to: {}'.format('images/segmentation/test/' +
                                         file_name[i]))

    print('INFO:finished!')
Beispiel #6
0
def my_json2dataset(json_file, lbl_names_all):
    ''' modified from labelme's json_to_dataset.py, 
    相比于原来的按照图中的标注来对label数字进行排序的方法,我直接指定了全部的label名称及其数字,这样的话所有标注的文件会统一,但是也只能适用于这个单一任务 
    @in     -json_file      -json文件
            -lbl_names_all  -所有的label的名称
    '''
    print(f'processing:{json_file}', end='')
    out_dir = osp.basename(json_file).replace(".", "_")
    out_dir = osp.join(osp.dirname(json_file), out_dir)

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

    data = json.load(open(json_file))
    imageData = data.get("imageData")

    if not imageData:
        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 = labelme.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
    label_name_to_value = {}
    for label_value, label_name in enumerate(lbl_names_all):
        label_name_to_value[label_name] = label_value

    lbl, _ = labelme.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 = imgviz.label2rgb(label=lbl,
                               img=imgviz.asgray(img),
                               label_names=label_names,
                               loc="rb")

    PIL.Image.fromarray(img).save(osp.join(out_dir, "img.png"))
    labelme.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('  done')
def make_image_with_mask(image_dir,label_dir):

  image = cv2.imread(image_dir)
  
  mask = cv2.imread(label_dir)
  mask = convert_from_color(mask[..., ::-1])

  labelviz_withimg = imgviz.label2rgb(mask, image)

  return labelviz_withimg
Beispiel #8
0
def test_label2rgb():
    data = imgviz.data.arc2017()
    H, W = data["class_label"].shape[:2]

    labelviz = imgviz.label2rgb(label=data["class_label"])
    assert labelviz.dtype == np.uint8
    assert labelviz.shape == (H, W, 3)

    labelviz = imgviz.label2rgb(label=data["class_label"], img=data["rgb"])
    assert labelviz.dtype == np.uint8
    assert labelviz.shape == (H, W, 3)

    labelviz = imgviz.label2rgb(
        label=data["class_label"],
        img=data["rgb"],
        label_names=data["class_names"],
    )
    assert labelviz.dtype == np.uint8
    assert labelviz.shape == (H, W, 3)
Beispiel #9
0
def label2rgb():
    data = imgviz.data.voc()

    rgb = data["rgb"]
    label = data["class_label"]

    label_names = [
        "{}:{}".format(i, n) for i, n in enumerate(data["class_names"])
    ]
    labelviz_withname1 = imgviz.label2rgb(label,
                                          label_names=label_names,
                                          font_size=25)
    labelviz_withname2 = imgviz.label2rgb(label,
                                          label_names=label_names,
                                          font_size=25,
                                          loc="lt")
    img = imgviz.color.rgb2gray(rgb)
    labelviz_withimg = imgviz.label2rgb(label, img=img)

    # -------------------------------------------------------------------------

    plt.figure(dpi=200)

    plt.subplot(131)
    plt.title("+img")
    plt.imshow(labelviz_withimg)
    plt.axis("off")

    plt.subplot(132)
    plt.title("loc=centroid")
    plt.imshow(labelviz_withname1)
    plt.axis("off")

    plt.subplot(133)
    plt.title("loc=lt")
    plt.imshow(labelviz_withname2)
    plt.axis("off")

    img = imgviz.io.pyplot_to_numpy()
    plt.close()

    return img
Beispiel #10
0
def json2img(json_file, out, index):
    if out is None:
        out_dir = osp.basename(json_file).replace(".", "_")
        out_dir = osp.join(osp.dirname(json_file), out_dir)
    else:
        out_dir = out
    mkdir(out_dir)
    data = json.load(open(json_file))
    imageData = data.get("imageData")

    if not imageData:
        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 = imgviz.label2rgb(label=lbl,
                               img=imgviz.asgray(img),
                               label_names=label_names,
                               loc="rb")
    img_name = str(index) + '.jpg'
    out_dir_raw = out_dir + '/raw'
    out_dir_label = out_dir + '/label'
    mkdir(out_dir_raw)
    mkdir(out_dir_label)
    PIL.Image.fromarray(img).save(osp.join(out_dir_raw, img_name))  #保存图片 1.jpg
    utils.lblsave(osp.join(out_dir_label, img_name.replace('.jpg', '.png')),
                  lbl)  #保存标签 1.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")

    logger.info("Saved to: {}".format(out_dir))
Beispiel #11
0
    def make_label_visualize_image(self, json_file):
        label_file = LabelFile(json_file)
        img = utils.img_data_to_arr(label_file.imageData)

        label_name_to_value = {"_background_": 0}
        for shape in sorted(label_file.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, label_file.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 = imgviz.label2rgb(
            label=lbl,
            img=imgviz.asgray(img),
            label_names=label_names,
            font_size=30,
            loc="rb",
        )

        return lbl_viz

        fig = plt.figure()
        ax1 = fig.add_subplot(111)
        ax1.imshow(img)
        ax2 = fig.add_subplot(111)
        ax2.imshow(lbl_viz)

        fig.canvas.draw()

        data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
        data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))

        # plt.subplot(121)
        # plt.imshow(img)
        # plt.subplot(122)
        # plt.imshow(lbl_viz)
        # plt.show()
        #
        # plt.draw()

        return data
    def __getitem__(self, i):
        example = self._dataset[i]

        rgb = example["color"]
        depth_viz = imgviz.depth2rgb(example["depth"])
        label_viz = imgviz.label2rgb(
            example["result"]["labels"],
            label_names=morefusion.datasets.ycb_video.class_names,
        )

        viz = imgviz.tile(
            [rgb, depth_viz, label_viz],
            shape=(1, 3),
            border=(255, 255, 255),
        )
        viz = imgviz.resize(viz, width=1000)
        return viz
Beispiel #13
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 = imgviz.label2rgb(
        label=lbl,
        img=imgviz.rgb2gray(img),
        label_names=label_names,
        font_size=30,
        loc='rb',
    )

    plt.subplot(121)
    plt.imshow(img)
    plt.subplot(122)
    plt.imshow(lbl_viz)
    plt.show()
def save_image_and_label(image, lbl, output_dir, label_names):
    """
    save image and label to output_dir
    :param image: image
    :param lbl: label
    :param output_dir: output directory
    :param label_names: label names
    :return:
    """
    PIL.Image.fromarray(image).save(osp.join(output_dir, 'img.png'))
    utils.lblsave(osp.join(output_dir, 'label.png'), lbl)
    lbl_viz = imgviz.label2rgb(lbl, imgviz.asgray(image), label_names=label_names, loc="rb")
    PIL.Image.fromarray(lbl_viz).save(osp.join(output_dir, 'label_viz.png'))

    with open(osp.join(output_dir, 'label_names.txt'), 'w', encoding="utf8") as label_f:
        for lbl_name in label_names:
            label_f.write(lbl_name + '\n')

    print(f"Saved to: {output_dir}")
    def __init__(
        self,
        rgb,
        pcd,
        instance_label,
        instance_ids,
        class_ids,
        Ts_cad2cam_true,
        Ts_cad2cam_pred=None,
    ):
        self._rgb = rgb
        self._pcd = pcd
        self._instance_label = instance_label
        self._instance_label_viz = imgviz.label2rgb(instance_label)
        self._instance_ids = instance_ids
        self._class_ids = dict(zip(instance_ids, class_ids))
        self._Ts_cad2cam_true = dict(zip(instance_ids, Ts_cad2cam_true))

        self._cads = {}
        for instance_id in self._instance_ids:
            class_id = self._class_ids[instance_id]
            cad = self._models.get_cad(class_id=class_id)
            cad.visual = cad.visual.to_color()
            self._cads[instance_id] = cad

        if Ts_cad2cam_pred is None:
            self._Ts_cad2cam_pred = {}
            nonnan = ~np.isnan(pcd).any(axis=2)
            for instance_id in instance_ids:
                mask = instance_label == instance_id
                centroid = pcd[nonnan & mask].mean(axis=0)
                T_cad2cam_pred = tf.translation_matrix(centroid)
                self._Ts_cad2cam_pred[instance_id] = T_cad2cam_pred
        else:
            assert len(instance_ids) == len(Ts_cad2cam_pred)
            self._Ts_cad2cam_pred = dict(zip(instance_ids, Ts_cad2cam_pred))
Beispiel #16
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

    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))
    imageData = data.get("imageData")

    if not imageData:
        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,
        "table": 1,
        "cup": 2,
        "bottle": 3,
        "glass": 4,
        "fork": 5,
        "knife": 6,
        "food": 7,
        "plate": 8
    }
    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 = imgviz.label2rgb(label=lbl,
                               img=imgviz.asgray(img),
                               label_names=label_names,
                               loc="rb")

    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.info("Saved to: {}".format(out_dir))
Beispiel #17
0
def main():
    # Only input:
    # Give a folder with only .json files
    label_path = r"/Users/frederikrogalski/Documents/Privates/Programieren/python/trainseg/data/trainseg/Masks/"

    list_path = os.listdir(label_path)
    for i in range(0, len(list_path)):
            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 = label_path + list_path[i]
            print(list_path[i])
            if args.out is None:
                out_dir = osp.basename(json_file).replace('.', '_')  # Return file name
                out_dir = osp.join(osp.dirname(json_file), out_dir)  # Combine directory and file name into one path
            else:
                out_dir = args.out
            if not osp.exists(out_dir):
                os.mkdir(out_dir)  # Used to create directories in digital permission mode

            data = json.load(open(json_file))
            imageData = data.get('imageData')

            if not imageData:
                imagePath = os.path.join(os.path.dirname(json_file), data['imagePath']) # os.path.dirname returns the file path
                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 = imgviz.label2rgb(
                label=lbl, img=imgviz.asgray(img), label_names=label_names, loc='rb'
            )

            PIL.Image.fromarray(img).save(osp.join(out_dir, "Images", f"Image{i+148}.png"))
            utils.lblsave(osp.join(out_dir, "Masks", f"Mask{i+148}.png"), lbl)
            #PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, f"Mask{i+148}.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.info('Saved to: {}'.format(out_dir))
Beispiel #18
0
import os.path as osp

import matplotlib.pyplot as plt

import imgviz


here = osp.dirname(osp.abspath(__file__))


if __name__ == '__main__':
    data = imgviz.data.arc2017()

    labelviz = imgviz.label2rgb(data['class_label'])

    label_names = [
        '{}:{}'.format(i, n) for i, n in enumerate(data['class_names'])
    ]
    labelviz_withname = imgviz.label2rgb(
        data['class_label'], label_names=label_names
    )
    img = imgviz.color.rgb2gray(data['rgb'])
    labelviz_withimg = imgviz.label2rgb(data['class_label'], img=img)

    # -------------------------------------------------------------------------

    fig = plt.figure(dpi=200)

    plt.subplot(141)
    plt.title('rgb')
    plt.imshow(data['rgb'])
Beispiel #19
0
def main():
    logger.warning('This script is aimed to convert the '
                   'JSON batch to gray map of DABNet format.')

    parser = argparse.ArgumentParser()
    parser.add_argument('--json-list', default=None)
    parser.add_argument('--label-file', default=None)
    args = parser.parse_args()

    # Load .json from list file
    if not osp.isfile(args.json_list):
        print("json_list doesn't existed!!")
        return

    with open(args.json_list, 'r') as f:
        json_files = f.readlines()
    json_files = [x.strip() for x in json_files]

    # Import label file
    if not osp.isfile(args.label_file):
        print("label_file doesn't existed!!")
        return
    label_name_to_value = importLabel(args.label_file)

    # main loop
    for i in range(0, len(json_files)):
        json_file = ''.join(json_files[i])

        out_dir = json_file.split('.')[0]

        data = json.load(open(json_file))
        imageData = data.get('imageData')

        if not imageData:
            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)

        # check label in json is in the label file or not
        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
                print(label_name, " is not in the label file")

        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 = imgviz.label2rgb(label=lbl,
                                   img=imgviz.asgray(img),
                                   label_names=label_names,
                                   loc='rb')

        # PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
        utils.lblsave_gray(out_dir + '.png', lbl)
        PIL.Image.fromarray(lbl_viz).save(out_dir + '_viz.png')

        logger.info('Saved to: {}'.format(out_dir))