File size: 3,782 Bytes
d21cb06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

# Copyright (C) 2020 Intel Corporation
#
# SPDX-License-Identifier: MIT

from glob import glob
import os
import os.path as osp

from datumaro.components.extractor import (DatasetItem, Label,
    LabelCategories, AnnotationType, SourceExtractor, Importer
)
from datumaro.components.converter import Converter


class ImagenetTxtPath:
    LABELS_FILE = 'synsets.txt'
    IMAGE_DIR = 'images'

class ImagenetTxtExtractor(SourceExtractor):
    def __init__(self, path, labels=None, image_dir=None):
        assert osp.isfile(path), path
        super().__init__(subset=osp.splitext(osp.basename(path))[0])

        if not image_dir:
            image_dir = ImagenetTxtPath.IMAGE_DIR
        self.image_dir = osp.join(osp.dirname(path), image_dir)

        if labels is None:
            labels = osp.join(osp.dirname(path), ImagenetTxtPath.LABELS_FILE)
            labels = self._parse_labels(labels)
        else:
            assert all(isinstance(e, str) for e in labels)

        self._categories = self._load_categories(labels)
        self._items = list(self._load_items(path).values())

    @staticmethod
    def _parse_labels(path):
        with open(path, encoding='utf-8') as labels_file:
            return [s.strip() for s in labels_file]

    def _load_categories(self, labels):
        return { AnnotationType.label: LabelCategories().from_iterable(labels) }

    def _load_items(self, path):
        items = {}
        with open(path, encoding='utf-8') as f:
            for line in f:
                item = line.split()
                item_id = item[0]
                label_ids = [int(id) for id in item[1:]]
                anno = []
                for label in label_ids:
                    assert 0 <= label and \
                        label < len(self._categories[AnnotationType.label]), \
                        "Image '%s': unknown label id '%s'" % (item_id, label)
                    anno.append(Label(label))
                items[item_id] = DatasetItem(id=item_id, subset=self._subset,
                    image=osp.join(self.image_dir, item_id + '.jpg'),
                    annotations=anno)
        return items


class ImagenetTxtImporter(Importer):
    @classmethod
    def find_sources(cls, path):
        subset_paths = [p for p in glob(osp.join(path, '*.txt'))
            if osp.basename(p) != ImagenetTxtPath.LABELS_FILE]
        sources = []
        for subset_path in subset_paths:
            sources += cls._find_sources_recursive(
                subset_path, '.txt', 'imagenet_txt')
        return sources


class ImagenetTxtConverter(Converter):
    DEFAULT_IMAGE_EXT = '.jpg'

    def apply(self):
        subset_dir = self._save_dir
        os.makedirs(subset_dir, exist_ok=True)

        extractor = self._extractor
        for subset_name, subset in self._extractor.subsets().items():
            annotation_file = osp.join(subset_dir, '%s.txt' % subset_name)
            labels = {}
            for item in subset:
                labels[item.id] = [str(p.label) for p in item.annotations
                    if p.type == AnnotationType.label]

                if self._save_images and item.has_image:
                    self._save_image(item,
                        osp.join(self._save_dir, ImagenetTxtPath.IMAGE_DIR,
                            self._make_image_filename(item)))

            with open(annotation_file, 'w', encoding='utf-8') as f:
                f.writelines(['%s %s\n' % (item_id, ' '.join(labels[item_id]))
                    for item_id in labels])

        labels_file = osp.join(subset_dir, ImagenetTxtPath.LABELS_FILE)
        with open(labels_file, 'w', encoding='utf-8') as f:
            f.write('\n'.join(l.name
                for l in extractor.categories()[AnnotationType.label])
            )