Example #1
0
    def from_json(cls, data, objects: VideoObjectCollection, frame_index, key_id_map: KeyIdMap = None):
        object_id = data.get(OBJECT_ID, None)
        object_key = None
        if OBJECT_KEY in data:
            object_key = uuid.UUID(data[OBJECT_KEY])

        if object_id is None and object_key is None:
            raise RuntimeError("Figure can not be deserialized from json: object_id or object_key are not found")

        if object_key is None:
            if key_id_map is None:
                raise RuntimeError("Figure can not be deserialized: key_id_map is None")
            object_key = key_id_map.get_object_key(object_id)
            if object_key is None:
                raise RuntimeError("Object with id={!r} not found in key_id_map".format(object_id))

        object = objects.get(object_key)
        if object is None:
            raise RuntimeError("Figure can not be deserialized: corresponding object {!r} not found in ObjectsCollection".format(object_key.hex))

        shape_str = data[ApiField.GEOMETRY_TYPE]
        geometry_json = data[ApiField.GEOMETRY]

        shape = GET_GEOMETRY_FROM_STR(shape_str)
        geometry = shape.from_json(geometry_json)

        key = uuid.UUID(data[KEY]) if KEY in data else uuid.uuid4()

        if key_id_map is not None:
            key_id_map.add_figure(key, data.get(ID, None))
        return cls(object, geometry, frame_index, key)
Example #2
0
    def from_json(cls, data, project_meta: ProjectMeta):
        '''
        The function from_json convert Label from json format to Label class object. If there is no ObjClass from
        input json format in ProjectMeta, it generate RuntimeError error.
        :param data: input label in json format
        :param project_meta: ProjectMeta class object
        :return: Label class object
        '''
        obj_class_name = data[LabelJsonFields.OBJ_CLASS_NAME]
        obj_class = project_meta.get_obj_class(obj_class_name)
        if obj_class is None:
            raise RuntimeError(
                f'Failed to deserialize a Label object from JSON: label class name {obj_class_name!r} '
                f'was not found in the given project meta.')

        if obj_class.geometry_type is AnyGeometry:
            geometry_type_actual = GET_GEOMETRY_FROM_STR(
                data[GEOMETRY_TYPE] if GEOMETRY_TYPE in
                data else data[GEOMETRY_SHAPE])
            geometry = geometry_type_actual.from_json(data)
        else:
            geometry = obj_class.geometry_type.from_json(data)

        return cls(geometry=geometry,
                   obj_class=obj_class,
                   tags=TagCollection.from_json(data[LabelJsonFields.TAGS],
                                                project_meta.tag_metas),
                   description=data.get(LabelJsonFields.DESCRIPTION, ""))
Example #3
0
def deserialize_geometry(geometry_type_str, geometry_json):
    '''
    Get geometry from json format
    :param geometry_type_str: str
    :param geometry_json: geometry in json format
    :return: geometry type object(Point, Polygon, PolyLine, Bitmap etc.)
    '''
    geometry_type = GET_GEOMETRY_FROM_STR(geometry_type_str)
    geometry = geometry_type.from_json(geometry_json)
    return geometry
def set_project_meta(api, project_id, state):
    fg_class = sly.ObjClass(state[const.FG_NAME],
                            GET_GEOMETRY_FROM_STR(state[const.FG_SHAPE]),
                            color=sly.color.hex2rgb(state[const.FG_COLOR]))
    st_class = sly.ObjClass(state[const.ST_NAME],
                            GET_GEOMETRY_FROM_STR(state[const.ST_SHAPE]),
                            color=sly.color.hex2rgb(state[const.ST_COLOR]))
    meta = sly.ProjectMeta(
        obj_classes=sly.ObjClassCollection([fg_class, st_class]))
    api.project.update_meta(
        project_id,
        sly.ProjectMeta().to_json())  # clear previous labels and classes
    api.project.update_meta(project_id, meta.to_json())
    return fg_class, st_class
Example #5
0
    def from_json(cls, data: dict) -> 'ObjClass':
        """
        Creates object from json serializable dictionary. See Supervisely Json format explanation here:
        https://docs.supervise.ly/ann_format/

        Returns:
            ObjClass
        """
        name = data[ObjClassJsonFields.NAME]
        geometry_type = GET_GEOMETRY_FROM_STR(data[ObjClassJsonFields.GEOMETRY_TYPE])
        color = hex2rgb(data[ObjClassJsonFields.COLOR])
        geometry_config = geometry_type.config_from_json(data.get(ObjClassJsonFields.GEOMETRY_CONFIG))
        sly_id = data.get(ObjClassJsonFields.ID, None)
        hotkey = data.get(ObjClassJsonFields.HOTKEY, "")
        return cls(name=name, geometry_type=geometry_type, color=color, geometry_config=geometry_config, sly_id=sly_id,
                   hotkey=hotkey)
Example #6
0
def prepare_meta(meta):
    new_classes = []
    for cls in meta.obj_classes:
        cls: sly.ObjClass
        new_classes.append(cls.clone(geometry_type=GET_GEOMETRY_FROM_STR("polygon")))

    meta = meta.clone(obj_classes=sly.ObjClassCollection(new_classes))
    return meta
Example #7
0
    def from_json(cls, data, objects: VideoObjectCollection, frame_index, key_id_map: KeyIdMap = None):
        '''
        The function from_json convert VideoFigure from json format to VideoFigure class object.
        :param data: input VideoFigure in json format
        :param objects: VideoObjectCollection
        :param frame_index: int
        :param key_id_map: KeyIdMap class object
        :return: VideoFigure class object
        '''
        object_id = data.get(OBJECT_ID, None)
        object_key = None
        if OBJECT_KEY in data:
            object_key = uuid.UUID(data[OBJECT_KEY])

        if object_id is None and object_key is None:
            raise RuntimeError("Figure can not be deserialized from json: object_id or object_key are not found")

        if object_key is None:
            if key_id_map is None:
                raise RuntimeError("Figure can not be deserialized: key_id_map is None")
            object_key = key_id_map.get_object_key(object_id)
            if object_key is None:
                raise RuntimeError("Object with id={!r} not found in key_id_map".format(object_id))

        object = objects.get(object_key)
        if object is None:
            raise RuntimeError("Figure can not be deserialized: corresponding object {!r} not found in ObjectsCollection".format(object_key.hex))

        shape_str = data[ApiField.GEOMETRY_TYPE]
        geometry_json = data[ApiField.GEOMETRY]

        shape = GET_GEOMETRY_FROM_STR(shape_str)
        geometry = shape.from_json(geometry_json)

        key = uuid.UUID(data[KEY]) if KEY in data else uuid.uuid4()

        if key_id_map is not None:
            key_id_map.add_figure(key, data.get(ID, None))

        class_id = data.get(CLASS_ID, None)
        labeler_login = data.get(LABELER_LOGIN, None)
        updated_at = data.get(UPDATED_AT, None)
        created_at = data.get(CREATED_AT, None)

        return cls(object, geometry, frame_index, key,
                   class_id=class_id, labeler_login=labeler_login, updated_at=updated_at, created_at=created_at)
Example #8
0
    def from_json(cls, data, project_meta: ProjectMeta):
        obj_class_name = data[LabelJsonFields.OBJ_CLASS_NAME]
        obj_class = project_meta.get_obj_class(obj_class_name)
        if obj_class is None:
            raise RuntimeError(
                f'Failed to deserialize a Label object from JSON: label class name {obj_class_name!r} '
                f'was not found in the given project meta.')

        if obj_class.geometry_type is AnyGeometry:
            geometry_type_actual = GET_GEOMETRY_FROM_STR(
                data[GEOMETRY_TYPE] if GEOMETRY_TYPE in
                data else data[GEOMETRY_SHAPE])
            geometry = geometry_type_actual.from_json(data)
        else:
            geometry = obj_class.geometry_type.from_json(data)

        return cls(geometry=geometry,
                   obj_class=obj_class,
                   tags=TagCollection.from_json(data[LabelJsonFields.TAGS],
                                                project_meta.tag_metas),
                   description=data.get(LabelJsonFields.DESCRIPTION, ""))
Example #9
0
def convert(api: sly.Api, task_id, context, state, app_logger):
    api.task.set_field(task_id, "data.started", True)

    TEAM_ID = int(os.environ['context.teamId'])
    WORKSPACE_ID = int(os.environ['context.workspaceId'])
    PROJECT_ID = int(os.environ['modal.state.slyProjectId'])
    src_project = api.project.get_info_by_id(PROJECT_ID)

    if src_project.type != str(sly.ProjectType.IMAGES):
        raise RuntimeError(
            "Project {!r} has type {!r}. App works only with type {!r}".format(
                src_project.name, src_project.type, sly.ProjectType.IMAGES))

    src_meta_json = api.project.get_meta(src_project.id)
    src_meta = sly.ProjectMeta.from_json(src_meta_json)

    new_classes = []
    need_action = False
    selectors = state["selectors"]
    for cls in src_meta.obj_classes:
        cls: sly.ObjClass
        dest = selectors[cls.name]
        if dest == REMAIN_UNCHANGED:
            new_classes.append(cls)
        else:
            need_action = True
            new_classes.append(
                cls.clone(geometry_type=GET_GEOMETRY_FROM_STR(dest)))

    if need_action is False:
        fields = [{
            "field": "state.showWarningDialog",
            "payload": True
        }, {
            "field": "data.started",
            "payload": False,
        }]
        api.task.set_fields(task_id, fields)
        return

    dst_project = api.project.create(src_project.workspace_id,
                                     src_project.name + "(new shapes)",
                                     description="new shapes",
                                     change_name_if_conflict=True)
    sly.logger.info('Destination project is created.',
                    extra={
                        'project_id': dst_project.id,
                        'project_name': dst_project.name
                    })
    dst_meta = src_meta.clone(obj_classes=sly.ObjClassCollection(new_classes))
    api.project.update_meta(dst_project.id, dst_meta.to_json())

    total_progress = api.project.get_images_count(src_project.id)
    current_progress = 0
    ds_progress = sly.Progress('Processing:', total_cnt=total_progress)
    for ds_info in api.dataset.get_list(src_project.id):

        dst_dataset = api.dataset.create(dst_project.id, ds_info.name)
        img_infos_all = api.image.get_list(ds_info.id)

        for img_infos in sly.batched(img_infos_all):
            img_names, img_ids, img_metas = zip(*((x.name, x.id, x.meta)
                                                  for x in img_infos))

            ann_infos = api.annotation.download_batch(ds_info.id, img_ids)
            anns = [
                sly.Annotation.from_json(x.annotation, src_meta)
                for x in ann_infos
            ]

            new_anns = [convert_annotation(ann, dst_meta) for ann in anns]

            new_img_infos = api.image.upload_ids(dst_dataset.id,
                                                 img_names,
                                                 img_ids,
                                                 metas=img_metas)
            new_img_ids = [x.id for x in new_img_infos]
            api.annotation.upload_anns(new_img_ids, new_anns)

            current_progress += len(img_infos)
            api.task.set_field(task_id, "data.progress",
                               int(current_progress * 100 / total_progress))
            ds_progress.iters_done_report(len(img_infos))

    api.task.set_output_project(task_id, dst_project.id, dst_project.name)

    # to get correct "reference_image_url"
    res_project = api.project.get_info_by_id(dst_project.id)
    fields = [{
        "field": "data.resultProject",
        "payload": dst_project.name,
    }, {
        "field": "data.resultProjectId",
        "payload": dst_project.id,
    }, {
        "field":
        "data.resultProjectPreviewUrl",
        "payload":
        api.image.preview_url(res_project.reference_image_url, 100, 100),
    }]
    api.task.set_fields(task_id, fields)
    my_app.stop()
Example #10
0
def deserialize_geometry(geometry_type_str, geometry_json):
    geometry_type = GET_GEOMETRY_FROM_STR(geometry_type_str)
    geometry = geometry_type.from_json(geometry_json)
    return geometry