Esempio n. 1
0
    def _save_item(self, subset_name, subset, item):
        if self._save_images and item.has_image:
            self._save_image(item,
                             subdir=osp.join(subset_name,
                                             IcdarPath.IMAGES_DIR))

        annotation = ''
        colormap = [(255, 255, 255)]
        anns = [a for a in item.annotations if a.type == AnnotationType.mask]
        if anns:
            anns = sorted(anns,
                          key=lambda a: int(a.attributes.get('index', 0)))
            group = anns[0].group
            for ann in anns:
                if ann.group != group or (not ann.group
                                          and anns[0].group != 0):
                    annotation += '\n'
                text = ''
                if ann.attributes:
                    if 'text' in ann.attributes:
                        text = ann.attributes['text']
                    if text == ' ':
                        annotation += '#'
                    if 'color' in ann.attributes and \
                            len(ann.attributes['color'].split()) == 3:
                        color = ann.attributes['color'].split()
                        colormap.append(
                            (int(color[0]), int(color[1]), int(color[2])))
                        annotation += ' '.join(p for p in color)
                    else:
                        raise Exception(
                            "Item %s: a mask must have "
                            "an RGB color attribute, e.g. '10 7 50'" % item.id)
                    if 'center' in ann.attributes:
                        annotation += ' %s' % ann.attributes['center']
                    else:
                        annotation += ' - -'
                bbox = ann.get_bbox()
                annotation += ' %s %s %s %s' % (bbox[0], bbox[1], bbox[0] +
                                                bbox[2], bbox[1] + bbox[3])
                annotation += ' \"%s\"' % text
                annotation += '\n'
                group = ann.group

            mask = CompiledMask.from_instance_masks(
                anns,
                instance_labels=[m.attributes['index'] + 1 for m in anns])
            mask = paint_mask(mask.class_mask,
                              {i: colormap[i]
                               for i in range(len(colormap))})
            save_image(osp.join(self._save_dir, subset_name,
                                item.id + '_GT' + IcdarPath.GT_EXT),
                       mask,
                       create_dir=True)

        anno_file = osp.join(self._save_dir, subset_name,
                             item.id + '_GT' + '.txt')
        os.makedirs(osp.dirname(anno_file), exist_ok=True)
        with open(anno_file, 'w', encoding='utf-8') as f:
            f.write(annotation)
    def save_annotations(self, item, path):
        annotation = ''
        colormap = [(255, 255, 255)]
        anns = [a for a in item.annotations if a.type == AnnotationType.mask]
        if anns:
            is_not_index = len(
                [p for p in anns if 'index' not in p.attributes])
            if is_not_index:
                raise Exception("Item %s: a mask must have"
                                "'index' attribute" % item.id)
            anns = sorted(anns, key=lambda a: a.attributes['index'])
            group = anns[0].group
            for ann in anns:
                if ann.group != group or (not ann.group
                                          and anns[0].group != 0):
                    annotation += '\n'
                text = ''
                if ann.attributes:
                    if 'text' in ann.attributes:
                        text = ann.attributes['text']
                    if text == ' ':
                        annotation += '#'
                    if 'color' in ann.attributes and \
                            len(ann.attributes['color'].split()) == 3:
                        color = ann.attributes['color'].split()
                        colormap.append(
                            (int(color[0]), int(color[1]), int(color[2])))
                        annotation += ' '.join(p for p in color)
                    else:
                        raise Exception(
                            "Item %s: a mask must have "
                            "an RGB color attribute, e. g. '10 7 50'" %
                            item.id)
                    if 'center' in ann.attributes:
                        annotation += ' %s' % ann.attributes['center']
                    else:
                        annotation += ' - -'
                bbox = ann.get_bbox()
                annotation += ' %s %s %s %s' % (bbox[0], bbox[1], bbox[0] +
                                                bbox[2], bbox[1] + bbox[3])
                annotation += ' \"%s\"' % text
                annotation += '\n'
                group = ann.group

            mask = CompiledMask.from_instance_masks(
                anns,
                instance_labels=[m.attributes['index'] + 1 for m in anns])
            mask = paint_mask(mask.class_mask,
                              {i: colormap[i]
                               for i in range(len(colormap))})
            save_image(osp.join(path, item.id + '_GT' + IcdarPath.GT_EXT),
                       mask,
                       create_dir=True)
        self.annotations[item.id] = annotation
Esempio n. 3
0
 def save_mask(self,
               path,
               mask,
               colormap=None,
               apply_colormap=True,
               dtype=np.uint8):
     if self._apply_colormap and apply_colormap:
         if colormap is None:
             colormap = self._categories[AnnotationType.mask].colormap
         mask = paint_mask(mask, colormap)
     save_image(path, mask, create_dir=True, dtype=dtype)
Esempio n. 4
0
    def test_can_paint_mask(self):
        mask = np.zeros((1, 3), dtype=np.uint8)
        mask[:, 0] = 0
        mask[:, 1] = 1
        mask[:, 2] = 2

        colormap = mask_tools.generate_colormap(3)

        expected = np.zeros((*mask.shape, 3), dtype=np.uint8)
        expected[:, 0] = colormap[0][::-1]
        expected[:, 1] = colormap[1][::-1]
        expected[:, 2] = colormap[2][::-1]

        actual = mask_tools.paint_mask(mask, colormap)

        self.assertTrue(np.array_equal(expected, actual),
            '%s\nvs.\n%s' % (expected, actual))
 def save_segm(self, path, mask, colormap=None):
     if self._apply_colormap:
         if colormap is None:
             colormap = self._categories[AnnotationType.mask].colormap
         mask = paint_mask(mask, colormap)
     save_image(path, mask, create_dir=True)
Esempio n. 6
0
 def paint(self, colormap):
     from datumaro.util.mask_tools import paint_mask
     return paint_mask(self.as_class_mask(), colormap)
Esempio n. 7
0
    def _save_item(self, subset_name, subset, item):
        if self._save_images and item.has_image:
            self._save_image(item,
                             subdir=osp.join(subset_name,
                                             IcdarPath.IMAGES_DIR))

        annotation = ''

        anns = [a for a in item.annotations if a.type == AnnotationType.mask]

        color_bank = iter(
            generate_colormap(len(anns), include_background=False).values())
        colormap = [(255, 255, 255)]
        used_colors = set(colormap)

        if anns:
            anns = sorted(anns,
                          key=lambda a: int(a.attributes.get('index', 0)))
            group = anns[0].group
            for i, ann in enumerate(anns):
                # Assign new color if it is not defined
                color = ann.attributes.get('color', '')
                if color:
                    color = color.split()
                    if len(color) != 3:
                        raise DatumaroError(
                            "Item %s: mask #%s has invalid color" %
                            (item.id, i))

                    color = tuple(map(int, color))
                else:
                    color = next(color_bank)
                    while color in used_colors:
                        color = next(color_bank)
                colormap.append(color)
                used_colors.add(color)

                text = ann.attributes.get('text', '')
                bbox = ann.get_bbox()

                if ann.group != group or (not ann.group
                                          and anns[0].group != 0):
                    annotation += '\n'
                if text == ' ':
                    annotation += '#'
                annotation += ' '.join(str(p) for p in color)
                annotation += ' %s' % ann.attributes.get('center', '- -')
                annotation += ' %s %s %s %s' % (bbox[0], bbox[1], bbox[0] +
                                                bbox[2], bbox[1] + bbox[3])
                annotation += ' \"%s\"' % text
                annotation += '\n'
                group = ann.group

            mask = CompiledMask.from_instance_masks(
                anns,
                instance_labels=[m.attributes['index'] + 1 for m in anns])
            mask = paint_mask(mask.class_mask,
                              {i: colormap[i]
                               for i in range(len(colormap))})
            save_image(osp.join(self._save_dir, subset_name,
                                item.id + '_GT' + IcdarPath.GT_EXT),
                       mask,
                       create_dir=True)

        anno_file = osp.join(self._save_dir, subset_name,
                             item.id + '_GT' + '.txt')
        os.makedirs(osp.dirname(anno_file), exist_ok=True)
        with open(anno_file, 'w', encoding='utf-8') as f:
            f.write(annotation)
Esempio n. 8
0
 def paint(self, colormap: Colormap) -> np.ndarray:
     """
     Applies a colormap to the mask and produces the resulting image.
     """
     from datumaro.util.mask_tools import paint_mask
     return paint_mask(self.as_class_mask(), colormap)