File size: 5,872 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# Copyright (C) 2020 Intel Corporation
#
# SPDX-License-Identifier: MIT

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

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


class VggFace2Path:
    ANNOTATION_DIR = "bb_landmark"
    IMAGE_EXT = '.jpg'
    BBOXES_FILE = 'loose_bb_'
    LANDMARKS_FILE = 'loose_landmark_'

class VggFace2Extractor(SourceExtractor):
    def __init__(self, path):
        if not osp.isfile(path):
            raise Exception("Can't read .csv annotation file '%s'" % path)
        self._path = path
        self._dataset_dir = osp.dirname(osp.dirname(path))

        subset = osp.splitext(osp.basename(path))[0]
        if subset.startswith(VggFace2Path.LANDMARKS_FILE):
            subset = subset.split('_')[2]
        super().__init__(subset=subset)

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

    def _load_categories(self):
        self._categories[AnnotationType.label] = LabelCategories()

    def _load_items(self, path):
        items = {}
        with open(path) as content:
            landmarks_table = list(csv.DictReader(content))

        for row in landmarks_table:
            item_id = row['NAME_ID']
            image_path = osp.join(self._dataset_dir, self._subset,
                item_id + VggFace2Path.IMAGE_EXT)
            annotations = []
            if len([p for p in row if row[p] == '']) == 0 and len(row) == 11:
                annotations.append(Points(
                    [float(row[p]) for p in row if p != 'NAME_ID']))
            if item_id in items and 0 < len(annotations):
                annotation = items[item_id].annotations
                annotation.append(annotations[0])
            else:
                items[item_id] = DatasetItem(id=item_id, subset=self._subset,
                    image=image_path, annotations=annotations)

        bboxes_path = osp.join(self._dataset_dir, VggFace2Path.ANNOTATION_DIR,
            VggFace2Path.BBOXES_FILE + self._subset + '.csv')
        if osp.isfile(bboxes_path):
            with open(bboxes_path) as content:
                bboxes_table = list(csv.DictReader(content))
            for row in bboxes_table:
                if len([p for p in row if row[p] == '']) == 0 and len(row) == 5:
                    item_id = row['NAME_ID']
                    annotations = items[item_id].annotations
                    annotations.append(Bbox(int(row['X']), int(row['Y']),
                        int(row['W']), int(row['H'])))
        return items

class VggFace2Importer(Importer):
    @classmethod
    def find_sources(cls, path):
        subset_paths = [p for p in glob(osp.join(path,
            VggFace2Path.ANNOTATION_DIR, '**.csv'), recursive=True)
            if not osp.basename(p).startswith(VggFace2Path.BBOXES_FILE)]
        sources = []
        for subset_path in subset_paths:
            sources += cls._find_sources_recursive(
                subset_path, '.csv', 'vgg_face2')
        return sources

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

    def apply(self):
        save_dir = self._save_dir

        os.makedirs(save_dir, exist_ok=True)
        for subset_name, subset in self._extractor.subsets().items():
            subset_dir = osp.join(save_dir, subset_name)
            bboxes_table = []
            landmarks_table = []
            for item in subset:
                if item.has_image and self._save_images:
                    self._save_image(item, osp.join(save_dir, subset_dir,
                        item.id + VggFace2Path.IMAGE_EXT))

                landmarks = [a for a in item.annotations
                    if a.type == AnnotationType.points]
                if landmarks:
                    for landmark in landmarks:
                        points = landmark.points
                        landmarks_table.append({'NAME_ID': item.id,
                            'P1X': points[0], 'P1Y': points[1],
                            'P2X': points[2], 'P2Y': points[3],
                            'P3X': points[4], 'P3Y': points[5],
                            'P4X': points[6], 'P4Y': points[7],
                            'P5X': points[8], 'P5Y': points[9]})
                else:
                    landmarks_table.append({'NAME_ID': item.id})

                bboxes = [a for a in item.annotations
                    if a.type == AnnotationType.bbox]
                if bboxes:
                    for bbox in bboxes:
                        bboxes_table.append({'NAME_ID': item.id, 'X': int(bbox.x),
                            'Y': int(bbox.y), 'W': int(bbox.w), 'H': int(bbox.h)})

            landmarks_path = osp.join(save_dir, VggFace2Path.ANNOTATION_DIR,
                VggFace2Path.LANDMARKS_FILE + subset_name + '.csv')
            os.makedirs(osp.dirname(landmarks_path), exist_ok=True)
            with open(landmarks_path, 'w', newline='') as file:
                columns = ['NAME_ID', 'P1X', 'P1Y', 'P2X', 'P2Y',
                    'P3X', 'P3Y', 'P4X', 'P4Y', 'P5X', 'P5Y']
                writer = csv.DictWriter(file, fieldnames=columns)
                writer.writeheader()
                writer.writerows(landmarks_table)

            if bboxes_table:
                bboxes_path = osp.join(save_dir, VggFace2Path.ANNOTATION_DIR,
                    VggFace2Path.BBOXES_FILE + subset_name + '.csv')
                os.makedirs(osp.dirname(bboxes_path), exist_ok=True)
                with open(bboxes_path, 'w', newline='') as file:
                    columns = ['NAME_ID', 'X', 'Y', 'W', 'H']
                    writer = csv.DictWriter(file, fieldnames=columns)
                    writer.writeheader()
                    writer.writerows(bboxes_table)