File size: 12,136 Bytes
b0d869f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
"""Five-level semantic hierarchy views of the unified part-whole records.

L1 fine part     annotated part label (object pixels without a part label become "<object> (other)")
L2 part group    derived: similar parts of one object merged (e.g. eyes+ears+head -> head)
L3 object        annotated whole category
L4 super-class   derived: animal / person / vehicle / household object
L5 foreground    derived: object vs background

Only L1 and L3 come from annotations. L2, L4 and L5 are fixed groupings of label names (the same
idea as merging face labels into coarser regions); the full mapping is written to
datasets/unified/five_level_taxonomy.json so it can be inspected or changed. Every L1 label has
exactly one parent at each coarser level, so the five label maps always nest.

  python code/tools/five_level_hierarchy.py taxonomy        # write the mapping
  python code/tools/five_level_hierarchy.py render          # draw examples per dataset
"""
import argparse
import json
from pathlib import Path
import re
import sys

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
import numpy as np
from PIL import Image, ImageOps

ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / 'code'))
from partwhole import UnifiedDataset, decode_mask, project_path  # noqa: E402

LEVELS = ('L1 fine part', 'L2 part group', 'L3 object', 'L4 super-class', 'L5 foreground')
ANIMALS = {'quadruped', 'biped', 'fish', 'bird', 'snake', 'reptile', 'cat', 'cow', 'dog', 'horse', 'sheep'}
VEHICLES = {'car', 'bicycle', 'boat', 'aeroplane', 'bus', 'motorbike', 'train', 'car (automobile)'}
HEAD = {'head', 'face', 'eye', 'ear', 'nose', 'mouth', 'jaw', 'teeth', 'beak', 'muzzle'}
LIMBS = {'leg', 'foot', 'paw', 'hoof', 'hand', 'arm', 'tail', 'wing', 'fin'}
WHEELS = {'wheel', 'tier', 'tire', 'chainwheel'}
VEHICLE_BODY = {'body', 'coach', 'locomotive', 'frame', 'roof', 'trunk', 'hood', 'door', 'window',
                'windowpane', 'windshield', 'bumper', 'fender', 'down', 'top', 'seat', 'stern'}
HANDLES = {'handle', 'strap', 'cable', 'wire', 'lace', 'string', 'grip', 'loop', 'buckle', 'headband',
           'neckband', 'lead', 'clip', 'cord', 'shaft', 'stem'}
SUPPORTS = {'leg', 'arm', 'foot', 'base', 'stretcher', 'rail', 'apron', 'pedestal', 'column', 'footrest', 'stile', 'skirt'}
LIDS = {'lid', 'cap', 'cover', 'top_cap', 'brush_cap', 'shade_cap', 'push_pull_cap', 'closure', 'hood'}


def words(name):
    return set(re.split(r'[\s_/:,]+|\band\b', name.lower())) - {''}


def super_class(obj):
    obj = obj.lower()
    if obj == 'person':
        return 'person'
    if obj in ANIMALS:
        return 'animal'
    if obj in VEHICLES:
        return 'vehicle'
    return 'household object'


def part_group(obj, part):
    if part == '(other)':
        return 'body'
    w, kind = words(part), super_class(obj)
    if kind in ('animal', 'person'):
        return 'head' if w & HEAD else 'limbs & tail' if w & LIMBS else 'body'
    if kind == 'vehicle':
        return 'wheels' if w & WHEELS else 'body' if w & VEHICLE_BODY else 'fittings'
    if part in LIDS or w & {'lid', 'cap', 'cover'}:
        return 'lids & caps'
    if part in HANDLES or w & HANDLES:
        return 'handles & straps'
    return 'legs & base' if w & SUPPORTS else 'body'


def split_label(dataset, node, categories):
    """(object, part) for a node; wholes give (object, '(other)')."""
    if dataset == 'PartImageNet':
        name = node['category'].split('/', 2)[2]
        if node['kind'] == 'whole':
            return name, '(other)'
        obj = name.split(' ', 1)[0]
        return obj, name.split(' ', 1)[1]
    if dataset == 'Pascal-Part':
        name = categories[node['category']]['display_name']
        return (name, '(other)') if node['kind'] == 'whole' else tuple(name.split('/', 1))
    name = node['category'].split('/', 2)[2]
    clean = lambda s: s.replace('_', ' ')
    if node['kind'] == 'whole':
        return clean(name), '(other)'
    obj, part = name.split(':', 1)
    return clean(obj), clean(part)


def chain(obj, part):
    group = part_group(obj, part)
    l1 = f'{obj} {part}' if part == '(other)' else f'{obj}/{part}'
    return [l1, f'{obj}/{group}', obj, super_class(obj), 'object']


def taxonomy(root):
    categories = json.loads((root / 'datasets/unified/categories.json').read_text())
    table = {}
    for dataset, cats in categories.items():
        table[dataset] = {}
        for key, meta in cats.items():
            if meta.get('is_background'):
                continue
            node = {'category': key, 'kind': meta['kind']}
            table[dataset][key] = dict(zip(LEVELS, chain(*split_label(dataset, node, cats))))
    target = root / 'datasets/unified/five_level_taxonomy.json'
    target.write_text(json.dumps({'levels': LEVELS, 'derived_levels': ['L2', 'L4', 'L5'],
                                  'note': __doc__.split('\n\n')[1], 'categories': table}, indent=1) + '\n')
    return target


def label_maps(record, categories):
    """Per-pixel labels at the five levels. Wholes first, then parts largest-first so small parts stay visible."""
    dataset = record['dataset']
    nodes = [n for n in record['nodes'] if n['area'] > 0 and n.get('mask_status', 'valid') == 'valid'
             and not categories.get(n['category'], {}).get('is_background', False)]
    nodes.sort(key=lambda n: (n['kind'] == 'part', -n['area']))
    index = np.zeros((record['height'], record['width']), dtype=np.int32)
    chains = [['background'] * 5]
    for node in nodes:
        chains.append(chain(*split_label(dataset, node, categories)))
        index[decode_mask(node['mask'])] = len(chains) - 1
    maps = []
    for level in range(5):
        names = [c[level] for c in chains]
        order = ['background'] + sorted(set(names) - {'background'},
                                         key=lambda n: -sum((index == i).sum() for i, m in enumerate(names) if m == n))
        lookup = np.array([order.index(n) for n in names])
        maps.append((lookup[index], order))
    return maps


def colorize(maps):
    """Colours follow the L1 labels; a merged label keeps the colour of its largest member (as in the example)."""
    palette = plt.get_cmap('tab20').colors + plt.get_cmap('Set2').colors + plt.get_cmap('Dark2').colors
    fine, fine_names = maps[0]
    colours = {0: (0, 0, 0)}
    for i in range(1, len(fine_names)):
        colours[i] = palette[(i - 1) % len(palette)]
    out = []
    for labels, names in maps:
        lut = np.zeros((len(names), 3))
        for j in range(1, len(names)):
            members, counts = np.unique(fine[labels == j], return_counts=True)
            if members.size:  # labels fully covered by smaller parts have no pixels left
                lut[j] = colours[int(members[np.argmax(counts)])]
        out.append((lut[labels], [(n, lut[j]) for j, n in enumerate(names) if (labels == j).any()]))
    return out


def render(root, dataset, split, records, output):
    categories = json.loads((root / 'datasets/unified/categories.json').read_text())[dataset]
    rows = len(records)
    figure = plt.figure(figsize=(25, 3.7 * rows))
    grid = figure.add_gridspec(rows, 11, width_ratios=[1, 1, 0.78] * 1 + [1, 0.78] * 4)
    for row, record in enumerate(records):
        path = project_path(root, record['image_path'])
        ax = figure.add_subplot(grid[row, 0])
        if path.is_file():
            with Image.open(path) as image:
                ax.imshow(ImageOps.exif_transpose(image).convert('RGB'))
            ax.set_title('Input', fontsize=13)
        else:
            ax.set_title('Input (image not on disk)', fontsize=11)
        ax.axis('off')
        ax.text(0.5, -0.06, f'{dataset} {split}\nimage {record["image_id"]}', ha='center', va='top',
                fontsize=9, transform=ax.transAxes)
        for level, (rgb, legend) in enumerate(colorize(label_maps(record, categories))):
            ax = figure.add_subplot(grid[row, 1 + 2 * level])
            ax.imshow(rgb)
            ax.set_title(LEVELS[level], fontsize=12)
            ax.set_xticks([]), ax.set_yticks([])
            shown = legend[:14] + ([(f'+{len(legend) - 14} more', (1, 1, 1))] if len(legend) > 14 else [])
            ax.legend([Patch(color=c) for _, c in shown], [n for n, _ in shown], loc='upper left',
                      bbox_to_anchor=(1.03, 1.0), fontsize=8, frameon=True, borderaxespad=0, handlelength=1.6)
            figure.add_subplot(grid[row, 2 + 2 * level]).axis('off')  # room for the legend
    figure.suptitle(f'{dataset}: five-level part-whole hierarchy (L1, L3 annotated; L2, L4, L5 derived label groupings)',
                    fontsize=14)
    figure.subplots_adjust(left=0.01, right=0.995, top=1 - 0.35 / rows, bottom=0.02, wspace=0.04, hspace=0.3)
    output.parent.mkdir(parents=True, exist_ok=True)
    figure.savefig(output, dpi=90)
    plt.close(figure)


def examples(root, dataset, split, count, image_ids=None, require_image=True):
    """Rank images by hierarchy richness (part groups, objects, super-classes) with at most four object
    types covering 20-100% of the image; pick the best ones with different object sets."""
    data = UnifiedDataset(root / 'datasets/unified' / dataset / (split + '.jsonl'), root)
    categories = json.loads((root / 'datasets/unified/categories.json').read_text())[dataset]
    if image_ids is not None:
        return [r for r in map(data.record, range(len(data))) if r['image_id'] in image_ids]
    scored = []
    for index in range(len(data)):
        record = data.record(index)
        if require_image and not project_path(root, record['image_path']).is_file():
            continue
        nodes = [n for n in record['nodes'] if n['area'] > 0 and n.get('mask_status', 'valid') == 'valid'
                 and not categories.get(n['category'], {}).get('is_background')]
        chains = [chain(*split_label(dataset, n, categories)) for n in nodes]
        cover = sum(n['area'] for n in nodes if n['kind'] == 'whole') / (record['width'] * record['height'])
        levels = [len({c[k] for c in chains}) for k in range(5)]
        if levels[0] >= 4 and levels[2] <= 4 and 0.2 <= cover <= 1.0:  # readable scenes: at most 4 object types
            scored.append((levels[1] + 2 * levels[2] + 3 * levels[3], index, record, frozenset(c[2] for c in chains)))
    chosen, seen = [], set()
    for _, _, record, objects in sorted(scored, key=lambda item: (-item[0], item[1])):
        if objects not in seen:
            chosen.append(record)
            seen.add(objects)
        if len(chosen) == count:
            break
    return chosen


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('command', choices=['taxonomy', 'render'])
    parser.add_argument('--root', type=Path, default=ROOT)
    parser.add_argument('--datasets', nargs='+', default=['PACO-LVIS', 'PartImageNet', 'Pascal-Part'])
    parser.add_argument('--count', type=int, default=3)
    parser.add_argument('--output', type=Path, default=ROOT / 'results/preparation/hierarchy')
    parser.add_argument('--list', action='store_true', help='print the chosen image paths without rendering')
    args = parser.parse_args()
    root = args.root.resolve()
    if args.command == 'taxonomy':
        print(taxonomy(root))
        return
    plans = {'PACO-LVIS': ('test', None), 'PartImageNet': ('val', None), 'Pascal-Part': ('val', None)}
    for dataset in args.datasets:
        split, ids = plans[dataset]
        records = examples(root, dataset, split, args.count, ids, require_image=not args.list)
        if args.list:
            print('\n'.join(r['image_path'] for r in records))
            continue
        if not records:
            print(dataset, 'no example with its image on disk; extract the source images first')
            continue
        target = args.output / f'{dataset}_five_levels.png'
        render(root, dataset, split, records, target)
        print(target, [r['image_id'] for r in records])


if __name__ == '__main__':
    main()