ZWG817 commited on
Commit
07c2d0f
·
verified ·
1 Parent(s): 1f3bf5a

Add original datasets and verified unified part-whole annotations

Browse files

Preserve PartImageNet OOD and processed Pascal-Part source archives, original Pascal MAT evidence, recovered test image, the versioned 33,520-record annotation bundle, English data documentation, loading helpers, provenance, and SHA256 manifest. Exclude model weights and Python environment.

.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ datasets/PartImageNet/images/test/n01494475/n01494475_742.JPEG filter=lfs diff=lfs merge=lfs -text
MANIFEST.json ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "repository": "ZWG817/CAP5405_Computer_Vision",
3
+ "repo_type": "dataset",
4
+ "image_records": 33520,
5
+ "sources": [
6
+ "PartImageNet OOD",
7
+ "Processed Pascal-Part"
8
+ ],
9
+ "source_archives_preserved": true,
10
+ "files": [
11
+ {
12
+ "path": "datasets/archives/PartImageNet_OOD.zip",
13
+ "bytes": 2910755506,
14
+ "sha256": "56de44826ab800e49f99d36ca9c1412e6e406e5d337100f01f4783e1e40aed35"
15
+ },
16
+ {
17
+ "path": "datasets/archives/Pascal_Part.zip",
18
+ "bytes": 1149438894,
19
+ "sha256": "5a07a8375617ee29947cee3ba2b500623b58b4d320ddaff03cb266eb874678e6"
20
+ },
21
+ {
22
+ "path": "datasets/archives/Pascal_Part_original_trainval.tar.gz",
23
+ "bytes": 80872607,
24
+ "sha256": "8e8e3a4b0b59ed54483081649de4de92c01ee4e5e8dd825a0cc36ae2e8b84732"
25
+ },
26
+ {
27
+ "path": "datasets/release/unified_partwhole_v1.zip",
28
+ "bytes": 71593420,
29
+ "sha256": "754dc4752761f502afdd88ff97f61849a8257a3b364a5b6acddfda9feae26edf"
30
+ },
31
+ {
32
+ "path": "datasets/release/package_report.json",
33
+ "bytes": 382,
34
+ "sha256": "5f98a0c34b5407387ff3afd90eecca408138929bc606dfabf19748cbc9dee5d0"
35
+ },
36
+ {
37
+ "path": "datasets/PartImageNet/images/test/n01494475/n01494475_742.JPEG",
38
+ "bytes": 109104,
39
+ "sha256": "b0f975b523f75d6511e930acb50a7571cd2c2572af128b40534e44a060ca29f8"
40
+ },
41
+ {
42
+ "path": "code/partwhole.py",
43
+ "bytes": 18808,
44
+ "sha256": "2b8f1f28aef3c638e71c0710bf353e20398a37ed9fc57527848268754537ad1b"
45
+ },
46
+ {
47
+ "path": "code/examples/read_unified.py",
48
+ "bytes": 2700,
49
+ "sha256": "0fc69f3d623446eb6ba5382c711da897cb4afaa40bd5321721d6fa7d9fee11cf"
50
+ },
51
+ {
52
+ "path": "code/tools/prepare_data.py",
53
+ "bytes": 4094,
54
+ "sha256": "c3318bdd738ae86f04bfc9e170282120d52f08d2dbbfab2f24e808a87c940a3b"
55
+ },
56
+ {
57
+ "path": "docs/UNIFIED_SCHEMA.md",
58
+ "bytes": 5150,
59
+ "sha256": "ce9a08f63bb4c58505675f0270cb550f3730c5a6dc2b502a1128ce02a65461fc"
60
+ },
61
+ {
62
+ "path": "results/preparation/recovered_image.json",
63
+ "bytes": 420,
64
+ "sha256": "99a04631a148fb7f8500ba0fa570f1704db2b6d8dbe988b92ffd5b82aaf96d5b"
65
+ },
66
+ {
67
+ "path": "results/data_delivery/partimagenet_example.png",
68
+ "bytes": 574063,
69
+ "sha256": "bfc597adaa7c86a6b12e284562d6db7dac931469eac7655e57fe34af625f8a84"
70
+ },
71
+ {
72
+ "path": "results/data_delivery/pascal_example.png",
73
+ "bytes": 553805,
74
+ "sha256": "d7a434ccc126b580702926528cfdfe8819f27368c80918f2c41a586a41b4184b"
75
+ },
76
+ {
77
+ "path": "docs/data/ADDITIONAL_DATASET_SCOPE.md",
78
+ "bytes": 1793,
79
+ "sha256": "43217e0c4729609fdeb66d34ad61e1b7500e4e8687a78ab86f2f197c61eccfc3"
80
+ },
81
+ {
82
+ "path": "docs/data/DATASET_CARD.md",
83
+ "bytes": 5968,
84
+ "sha256": "df0f63c3baca80f8166cb8d51ea43b745532cb92ae1364d4d8c602e4824581fd"
85
+ },
86
+ {
87
+ "path": "docs/data/PASCAL_LABELS.md",
88
+ "bytes": 3185,
89
+ "sha256": "06d09298de4479caa7035730371a14e259003d5a07e7b70dbf1750508532294a"
90
+ },
91
+ {
92
+ "path": "docs/data/QUALITY_POLICY.md",
93
+ "bytes": 2675,
94
+ "sha256": "3a0140531a032ecd292a7d5ad4d1036649e7fd79273622430b0d72e031180ec1"
95
+ },
96
+ {
97
+ "path": "docs/data/SOURCES_AND_LICENSES.md",
98
+ "bytes": 2572,
99
+ "sha256": "7bda580261a2b87f598a819d73aa41eb71ba8921125c6b0d2ce107b03f70b865"
100
+ },
101
+ {
102
+ "path": "README.md",
103
+ "bytes": 7776,
104
+ "sha256": "f5c4213e4053ec6aa682d942f921a5b78f3586b6b95c73a004d3794ad0ea1355"
105
+ }
106
+ ]
107
+ }
README.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ license: other
5
+ license_name: source-specific-terms
6
+ license_link: https://huggingface.co/datasets/ZWG817/CAP5405_Computer_Vision/blob/main/docs/data/SOURCES_AND_LICENSES.md
7
+ task_categories:
8
+ - image-segmentation
9
+ tags:
10
+ - computer-vision
11
+ - hierarchical-segmentation
12
+ - part-whole
13
+ - partimagenet
14
+ - pascal-part
15
+ - course-project
16
+ size_categories:
17
+ - 10K<n<100K
18
+ ---
19
+
20
+ # CAP5405 Computer Vision: unified part-whole data
21
+
22
+ Prepared by **Wugeng Zheng and Rafid Ahmed** for the UCF Computer Vision project, *Seq2Seq Models for Hierarchical Image Segmentation*. The course proposal identifies CAP5415; this repository keeps the requested CAP5405 name.
23
+
24
+ The unified annotations represent **33,520 images** from PartImageNet OOD and the supplied processed Pascal-Part subset. Both sources use one image-record schema with compressed COCO RLE masks, explicit parent references, source label IDs, and quality flags. The repository also preserves the original input archives so teammates can restore images and source labels alongside the converted records.
25
+
26
+ ## Files
27
+
28
+ | Path | Contents |
29
+ | --- | --- |
30
+ | `datasets/release/unified_partwhole_v1.zip` | All 33,520 unified records, schema, category/name metadata, converter/loader examples, quality evidence, and an embedded SHA256 manifest; annotation-only ZIP, 71,593,420 bytes |
31
+ | `datasets/release/package_report.json` | Verification report for the versioned annotation ZIP |
32
+ | `datasets/archives/PartImageNet_OOD.zip` | Original PartImageNet OOD images and COCO annotations, 2,910,755,506 bytes |
33
+ | `datasets/archives/Pascal_Part.zip` | Original processed Pascal-Part images and part/whole PNG labels, 1,149,438,894 bytes |
34
+ | `datasets/archives/Pascal_Part_original_trainval.tar.gz` | Original named Pascal-Part MAT annotations used to reconstruct category metadata, 80,872,607 bytes |
35
+ | `datasets/PartImageNet/images/test/n01494475/n01494475_742.JPEG` | Original test image missing from the OOD archive, recovered from the same authors' official Seg archive |
36
+ | `code/` | Existing shared loader, record-inspection example, and original-archive preparation tool |
37
+ | `docs/data/` | Dataset card, sources/licenses, label evidence, quality policy, and planned additional-source scope |
38
+ | `docs/UNIFIED_SCHEMA.md` | Record and mask format |
39
+ | `results/` | Recovery provenance and representative annotation previews |
40
+ | `MANIFEST.json` | File sizes and SHA256 for this upload's payload; excludes itself |
41
+
42
+ The original archives and annotation ZIP are preserved byte for byte. The annotation ZIP is the versioned 2026-11-01 course bundle; its embedded documentation records that historical local release. This repository homepage provides the current English download and restoration instructions. Model weights, the Python environment, and bulk model predictions are kept separately.
43
+
44
+ ## Dataset splits
45
+
46
+ | Source | Train | Validation | Test | Total |
47
+ | --- | ---: | ---: | ---: | ---: |
48
+ | PartImageNet OOD | 16,540 | 2,957 | 4,598 | 24,095 |
49
+ | Processed Pascal-Part | 4,653 | 4,772 | — | 9,425 |
50
+ | Total | 21,193 | 7,729 | 4,598 | 33,520 |
51
+
52
+ The processed Pascal subset is not the full original 10,103-image Pascal-Part release. Source splits and numeric category IDs are retained. The combined records contain 45,749 whole nodes and 170,497 part nodes; these are semantic nodes, not object-instance counts.
53
+
54
+ ## Download and restore
55
+
56
+ Use the Hugging Face CLI from a local working directory:
57
+
58
+ ```powershell
59
+ hf download ZWG817/CAP5405_Computer_Vision --repo-type dataset --local-dir .
60
+ ```
61
+
62
+ For annotations without source image archives:
63
+
64
+ ```powershell
65
+ hf download ZWG817/CAP5405_Computer_Vision --repo-type dataset --include "datasets/release/*" "docs/*" "code/*" "README.md" "MANIFEST.json" --local-dir .
66
+ ```
67
+
68
+ Extract `datasets/release/unified_partwhole_v1.zip` into the working project root. It contains `datasets/unified/`, supporting code/documentation, and an embedded `manifest.json`. Preserve any newer project code/docs when merging an existing checkout; the ZIP also contains a historical root README. Extracting into a separate directory first makes that merge easy to inspect.
69
+
70
+ The source PartImageNet archive contains nested train/val/test ZIPs. `code/tools/prepare_data.py --root <project-root>` expands both source ZIPs into the expected image/annotation layout while preserving their splits. Use the project's prepared Python environment and set TEMP/TMP/TMPDIR to the daily task-cache directory before extraction. The recovered test image is already supplied at its final relative path; keep it alongside the extracted OOD test images. The MAT archive is provenance evidence and is not required for loading the processed PNGs.
71
+
72
+ Unified JSONL files live at `datasets/unified/<dataset>/<split>.jsonl`. Use `UnifiedDataset.record(index)` to read annotations without image files; `UnifiedDataset[index]` loads the image and masks as well. `code/examples/read_unified.py` prints source-backed category names, candidate nodes, and semantic conflicts. NumPy, Pillow, pycocotools, and tqdm are needed by the existing loader. See [the dataset card](docs/data/DATASET_CARD.md) and [schema](docs/UNIFIED_SCHEMA.md) for details. This is an archive-based project dataset; the shared loader reads its nested JSONL records directly.
73
+
74
+ ## Annotation semantics and quality
75
+
76
+ PartImageNet whole masks are unions of decodable parts in the same supercategory. Pascal nodes preserve the processed whole/part PNGs through pixel intersections. These are two-level semantic relationships; they do not create instance identities or complete anatomical trees.
77
+
78
+ All 33,520 records passed conversion-integrity checks with zero conversion issues. Original data quality is recorded separately:
79
+
80
+ - PartImageNet contains 168 malformed source geometries, retained with coordinates and explicit flags. The default loader omits unusable masks rather than inventing geometry.
81
+ - Six PartImageNet images have EXIF rotation; image loading follows display orientation to match annotation coordinates.
82
+ - Pascal whole background is 16, part background is 54, with no observed ignore label. Source-backed display names are provided for 16 foreground whole classes and 54 part groups.
83
+ - The processed Pascal labels contain part/whole semantic conflicts in 512 train and 547 validation images. The original pixels and numeric IDs remain unchanged; quality reports distinguish source conflicts from conversion fidelity.
84
+
85
+ The annotation ZIP SHA256 is `754dc4752761f502afdd88ff97f61849a8257a3b364a5b6acddfda9feae26edf`. Its 25 payload files passed ZIP CRC and SHA256 readback checks. `MANIFEST.json` supplies the hashes for the uploaded archives and supporting files.
86
+
87
+ ## Sources and terms
88
+
89
+ PartImageNet OOD and processed Pascal-Part archives come from [turkeyju/PartImageNet](https://huggingface.co/datasets/turkeyju/PartImageNet), revision `cfa2edf3cf5ffbede2bd1fc934edca0aba99f042`. The recovered image comes from that release's `PartImageNet_Seg.zip`. Original named Pascal-Part annotations come from [the authors' dataset page](https://roozbehm.info/pascal-parts/pascal-parts.html), file `trainval.tar.gz`.
90
+
91
+ This repository preserves source-specific terms and attribution. The upstream HF dataset metadata states Apache-2.0; ImageNet/VOC-origin image conditions remain separate, and that repository label does not establish all image rights. No new blanket license is assigned to all images, annotations, and project code. See [sources and licenses](docs/data/SOURCES_AND_LICENSES.md) for exact URLs, hashes, versions, and provenance.
92
+
93
+ PACO-LVIS is a planned extension and is not included. This upload contains the two completed data sources and does not claim completion of the remaining ImageNet/VOC/DensePose experiment branches or the final team submission.
code/examples/read_unified.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read one unified image and its source-backed category metadata."""
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+ import sys
6
+
7
+ ROOT=Path(__file__).resolve().parents[2]
8
+ sys.path.insert(0,str(ROOT/'code'))
9
+ from partwhole import UnifiedDataset,visualize
10
+
11
+
12
+ def main():
13
+ parser=argparse.ArgumentParser(description=__doc__)
14
+ parser.add_argument('--root',type=Path,default=ROOT)
15
+ parser.add_argument('--dataset',choices=['PartImageNet','Pascal-Part'],default='Pascal-Part')
16
+ parser.add_argument('--split',default='val')
17
+ parser.add_argument('--index',type=int,default=0)
18
+ parser.add_argument('--output',type=Path,help='Optional original/whole/part preview')
19
+ args=parser.parse_args()
20
+ annotation=args.root/'datasets/unified'/args.dataset/(args.split+'.jsonl')
21
+ dataset=UnifiedDataset(annotation,args.root)
22
+ record=dataset.record(args.index)
23
+ categories=json.loads((args.root/'datasets/unified/categories.json').read_text())[args.dataset]
24
+ examples=[]
25
+ for node in record['nodes'][:8]:
26
+ metadata=categories[node['category']]
27
+ examples.append({'id':node['id'],'numeric_or_source_id':node['source_label_id'],
28
+ 'category':node['category'],'name':metadata.get('display_name',node['category']),
29
+ 'is_background':metadata.get('is_background',False),'mask_status':node.get('mask_status','valid')})
30
+ nodes={node['id']:node for node in record['nodes']}
31
+ candidates,conflicts=[],[]
32
+ pascal=(json.loads((args.root/'datasets/unified/Pascal-Part/label_metadata.json').read_text())
33
+ if args.dataset=='Pascal-Part' else None)
34
+ for node in record['nodes']:
35
+ meta=categories[node['category']]
36
+ if meta.get('is_background',False) or node.get('mask_status','valid')!='valid' or node['area']==0:
37
+ continue
38
+ if pascal is not None and node['kind']=='part':
39
+ expected=pascal['part'][str(node['source_label_id'])]['parent_whole_id']
40
+ actual=nodes[node['parent_id']]['source_label_id']
41
+ if expected!=actual:
42
+ conflicts.append(node['id'])
43
+ continue
44
+ candidates.append(node['id'])
45
+ print(json.dumps({'dataset':args.dataset,'records':len(dataset),'image_id':record['image_id'],
46
+ 'size':[record['width'],record['height']],'node_examples':examples,
47
+ 'foreground_candidate_node_ids':candidates,'semantic_conflict_node_ids':conflicts},indent=2))
48
+ if args.output:
49
+ sample=dataset[args.index]
50
+ assert sample['image'].size==(record['width'],record['height'])
51
+ visualize(args.root,annotation,args.index,args.output)
52
+ print('Preview:',args.output)
53
+
54
+
55
+ if __name__=='__main__':
56
+ main()
57
+
code/partwhole.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lossless part/whole annotation conversion, validation and loading.
2
+
3
+ Category IDs are namespaced by dataset. Pascal labels remain numeric because
4
+ its supplied archive does not contain an authoritative class-name mapping.
5
+ """
6
+ import argparse
7
+ from collections import Counter, defaultdict
8
+ import json
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ from PIL import Image, ImageDraw, ImageOps
13
+ from pycocotools import mask as coco_mask
14
+ from tqdm import tqdm
15
+
16
+ ROOT = Path(__file__).resolve().parents[1]
17
+ VERSION = '1.0'
18
+
19
+
20
+ def encode_mask(mask):
21
+ encoded = coco_mask.encode(np.asfortranarray(mask, dtype=np.uint8))
22
+ return {'size': encoded['size'], 'counts': encoded['counts'].decode('ascii')}
23
+
24
+
25
+ def decode_mask(rle):
26
+ return coco_mask.decode({'size': rle['size'], 'counts': rle['counts'].encode('ascii')}).astype(bool)
27
+
28
+
29
+ def project_path(root, relative):
30
+ path = (root / relative).resolve()
31
+ if not path.is_relative_to(root.resolve()):
32
+ raise ValueError(f'Path outside dataset root: {relative}')
33
+ return path
34
+
35
+
36
+ def node(node_id, parent, category, mask, source_label, provenance):
37
+ return {'id': node_id, 'parent_id': parent, 'level': 0 if parent is None else 1,
38
+ 'kind': 'whole' if parent is None else 'part', 'category': category,
39
+ 'source_label_id': source_label, 'provenance': provenance,
40
+ 'area': int(mask.sum()), 'mask': encode_mask(mask)}
41
+
42
+
43
+ def source_mask(coco, ann):
44
+ segmentation = ann['segmentation']
45
+ if isinstance(segmentation, list):
46
+ valid = [polygon for polygon in segmentation if len(polygon) >= 6 and len(polygon) % 2 == 0]
47
+ if len(valid) != len(segmentation) or not valid:
48
+ im = coco.imgs[ann['image_id']]
49
+ mask = np.zeros((im['height'], im['width']), dtype=bool)
50
+ if valid:
51
+ mask = coco.annToMask(dict(ann, segmentation=valid)).astype(bool)
52
+ return mask, 'partial_invalid_source_geometry' if valid else 'invalid_source_geometry'
53
+ return coco.annToMask(ann).astype(bool), 'valid'
54
+
55
+
56
+ def partimagenet_records(root, split):
57
+ from pycocotools.coco import COCO
58
+ source = root / 'datasets/PartImageNet/annotations' / (split + '.json')
59
+ coco = COCO(str(source))
60
+ for im in sorted(coco.imgs.values(), key=lambda item: item['id']):
61
+ filename = im['file_name']
62
+ image = root / 'datasets/PartImageNet/images' / split / filename[:9] / filename
63
+ groups = defaultdict(list)
64
+ nodes = []
65
+ for ann in sorted(coco.imgToAnns.get(im['id'], []), key=lambda item: item['id']):
66
+ category = coco.cats[ann['category_id']]
67
+ parent = 'whole:' + category['supercategory']
68
+ mask, mask_status = source_mask(coco, ann)
69
+ groups[category['supercategory']].append(mask)
70
+ entry = node('part:' + str(ann['id']), parent,
71
+ 'PartImageNet/part/' + category['name'], mask,
72
+ ann['category_id'], 'source_coco_annotation')
73
+ entry['source_annotation_id'] = ann['id']
74
+ entry['source_segmentation'] = ann['segmentation']
75
+ entry['mask_status'] = mask_status
76
+ nodes.append(entry)
77
+ for category, masks in sorted(groups.items()):
78
+ nodes.insert(0, node('whole:' + category, None,
79
+ 'PartImageNet/whole/' + category, np.logical_or.reduce(masks),
80
+ category, 'union_of_source_parts_same_supercategory'))
81
+ yield {'schema_version': VERSION, 'dataset': 'PartImageNet', 'split': split,
82
+ 'image_id': str(im['id']), 'image_path': image.relative_to(root).as_posix(),
83
+ 'image_available': image.is_file(), 'width': im['width'], 'height': im['height'],
84
+ 'source_path': source.relative_to(root).as_posix(),
85
+ 'hierarchy_semantics': 'semantic_groups_not_instance_ids', 'nodes': nodes}
86
+
87
+
88
+ def pascal_records(root, split):
89
+ base = root / 'datasets/Pascal-Part'
90
+ images = {p.stem: p for p in (base / 'JPEGImages' / split).iterdir() if p.is_file()}
91
+ for part_path in sorted((base / 'annotations' / split).glob('*.png')):
92
+ whole_path = base / 'annotations' / (split + '_whole') / part_path.name
93
+ with Image.open(part_path) as image:
94
+ parts = np.array(image)
95
+ with Image.open(whole_path) as image:
96
+ wholes = np.array(image)
97
+ if parts.ndim != 2 or parts.shape != wholes.shape:
98
+ raise ValueError(f'Expected paired integer label maps: {part_path}')
99
+ height, width = parts.shape
100
+ metadata_path = part_path.with_suffix('.json')
101
+ if metadata_path.is_file():
102
+ metadata = json.loads(metadata_path.read_text(encoding='utf-8'))
103
+ if (metadata['imgHeight'], metadata['imgWidth']) != parts.shape:
104
+ raise ValueError(f'Metadata dimensions differ: {metadata_path}')
105
+ nodes = []
106
+ # Keep every source value, including background/void values. Intersections
107
+ # preserve the entire part raster without inventing an instance identity.
108
+ for label in np.unique(wholes):
109
+ label = int(label)
110
+ mask = wholes == label
111
+ parent = 'whole:' + str(label)
112
+ nodes.append(node(parent, None, f'Pascal-Part/whole/source_label_{label}',
113
+ mask, label, 'source_whole_label_map'))
114
+ for part in np.unique(parts[mask]):
115
+ part = int(part)
116
+ nodes.append(node(f'part:{part}:whole:{label}', parent,
117
+ f'Pascal-Part/part/source_label_{part}',
118
+ mask & (parts == part), part, 'source_part_whole_intersection'))
119
+ image = images[part_path.stem]
120
+ yield {'schema_version': VERSION, 'dataset': 'Pascal-Part', 'split': split,
121
+ 'image_id': part_path.stem, 'image_path': image.relative_to(root).as_posix(),
122
+ 'image_available': True, 'width': width, 'height': height,
123
+ 'source_path': part_path.relative_to(root).as_posix(),
124
+ 'source_whole_path': whole_path.relative_to(root).as_posix(),
125
+ 'hierarchy_semantics': 'semantic_label_intersections_all_source_values',
126
+ 'nodes': nodes}
127
+
128
+
129
+ def convert(root):
130
+ output = root / 'datasets/unified'
131
+ output.mkdir(parents=True, exist_ok=True)
132
+ summary = {}
133
+ categories = defaultdict(dict)
134
+ for dataset, splits, factory in [('PartImageNet', ('train', 'val', 'test'), partimagenet_records),
135
+ ('Pascal-Part', ('train', 'val'), pascal_records)]:
136
+ for split in splits:
137
+ target = output / dataset / (split + '.jsonl')
138
+ target.parent.mkdir(exist_ok=True)
139
+ stats = Counter()
140
+ with target.open('w', encoding='utf-8') as stream:
141
+ for record in tqdm(factory(root, split), desc=f'{dataset}/{split}', mininterval=3, ascii=True):
142
+ stream.write(json.dumps(record, separators=(',', ':')) + '\n')
143
+ stats['images'] += 1
144
+ stats['missing_images'] += not record['image_available']
145
+ for entry in record['nodes']:
146
+ stats[entry['kind'] + '_nodes'] += 1
147
+ stats['empty_masks'] += entry['area'] == 0
148
+ stats['invalid_source_geometry'] += entry.get('mask_status', 'valid') != 'valid'
149
+ categories[dataset][entry['category']] = {'kind': entry['kind'],
150
+ 'source_label_id': entry['source_label_id'],
151
+ 'name_status': 'source_numeric_id_only' if dataset == 'Pascal-Part' else 'source_category_name'}
152
+ summary[dataset + '/' + split] = dict(stats)
153
+ (output / 'categories.json').write_text(json.dumps(categories, indent=2) + '\n', encoding='utf-8')
154
+ (output / 'conversion_summary.json').write_text(json.dumps(summary, indent=2) + '\n', encoding='utf-8')
155
+ return summary
156
+
157
+
158
+ class UnifiedDataset:
159
+ """Random access JSONL loader, compatible with torch DataLoader (collate_fn=list)."""
160
+ def __init__(self, annotations, root=ROOT):
161
+ self.path = Path(annotations)
162
+ self.root = Path(root).resolve()
163
+ self.offsets = []
164
+ with self.path.open('rb') as stream:
165
+ while True:
166
+ position = stream.tell()
167
+ if not stream.readline():
168
+ break
169
+ self.offsets.append(position)
170
+
171
+ def __len__(self):
172
+ return len(self.offsets)
173
+
174
+ def record(self, index):
175
+ with self.path.open('rb') as stream:
176
+ stream.seek(self.offsets[index])
177
+ return json.loads(stream.readline())
178
+
179
+ def __getitem__(self, index):
180
+ record = self.record(index)
181
+ with Image.open(project_path(self.root, record['image_path'])) as image:
182
+ image = ImageOps.exif_transpose(image).convert('RGB')
183
+ return {'record': record, 'image': image,
184
+ 'masks': {entry['id']: decode_mask(entry['mask']) for entry in record['nodes']
185
+ if entry.get('mask_status', 'valid') == 'valid'},
186
+ 'invalid_node_ids': [entry['id'] for entry in record['nodes']
187
+ if entry.get('mask_status', 'valid') != 'valid']}
188
+
189
+
190
+ def validate_record(record, root, check_source=True):
191
+ errors = []
192
+ image_path = project_path(root, record['image_path'])
193
+ if image_path.is_file():
194
+ with Image.open(image_path) as image:
195
+ if ImageOps.exif_transpose(image).size != (record['width'], record['height']):
196
+ errors.append('image_dimension_mismatch')
197
+ else:
198
+ errors.append('missing_image:' + record['image_path'])
199
+ if record['image_available'] != image_path.is_file():
200
+ errors.append('image_availability_flag_mismatch')
201
+ entries = {entry['id']: entry for entry in record['nodes']}
202
+ if len(entries) != len(record['nodes']):
203
+ errors.append('duplicate_node_id')
204
+ masks = {}
205
+ for entry in record['nodes']:
206
+ mask = decode_mask(entry['mask'])
207
+ masks[entry['id']] = mask
208
+ if mask.shape != (record['height'], record['width']):
209
+ errors.append('mask_dimension_mismatch:' + entry['id'])
210
+ if int(mask.sum()) != entry['area']:
211
+ errors.append('mask_area_mismatch:' + entry['id'])
212
+ parent = entry['parent_id']
213
+ if parent is None and (entry['level'] != 0 or entry['kind'] != 'whole'):
214
+ errors.append('invalid_root_node:' + entry['id'])
215
+ if parent is not None and entry['kind'] != 'part':
216
+ errors.append('invalid_child_node:' + entry['id'])
217
+ if parent is not None and (parent not in entries or entries[parent]['level'] + 1 != entry['level']):
218
+ errors.append('invalid_parent_or_level:' + entry['id'])
219
+ seen = {entry['id']}
220
+ while parent in entries:
221
+ if parent in seen:
222
+ errors.append('cycle:' + entry['id'])
223
+ break
224
+ seen.add(parent)
225
+ parent = entries[parent]['parent_id']
226
+ for entry in record['nodes']:
227
+ parent = entry['parent_id']
228
+ if parent in masks and masks[parent].shape == masks[entry['id']].shape:
229
+ if np.any(masks[entry['id']] & ~masks[parent]):
230
+ errors.append('part_outside_parent:' + entry['id'])
231
+ if check_source and record['dataset'] == 'Pascal-Part':
232
+ with Image.open(project_path(root, record['source_path'])) as image:
233
+ original_part = np.array(image)
234
+ with Image.open(project_path(root, record['source_whole_path'])) as image:
235
+ original_whole = np.array(image)
236
+ for kind, original in [('part', original_part), ('whole', original_whole)]:
237
+ restored = np.full(original.shape, -1, dtype=np.int32)
238
+ coverage = np.zeros(original.shape, dtype=np.uint8)
239
+ for entry in record['nodes']:
240
+ if entry['kind'] == kind:
241
+ mask = masks[entry['id']]
242
+ restored[mask] = entry['source_label_id']
243
+ coverage += mask
244
+ if not np.array_equal(restored, original) or np.any(coverage != 1):
245
+ errors.append('source_raster_not_lossless:' + kind)
246
+ return errors
247
+
248
+
249
+ def validate(root):
250
+ from jsonschema import Draft202012Validator
251
+ schema = json.loads((root / 'datasets/unified/schema.json').read_text(encoding='utf-8-sig'))
252
+ schema_validator = Draft202012Validator(schema)
253
+ summary = {'splits': {}, 'issues': [], 'source_geometry_issues': [], 'duplicate_image_paths_across_splits': []}
254
+ paths = {}
255
+ image_ids = set()
256
+ for path in sorted((root / 'datasets/unified').glob('*/*.jsonl')):
257
+ dataset = UnifiedDataset(path, root)
258
+ stats = Counter()
259
+ source_coco = None
260
+ for index in tqdm(range(len(dataset)), desc=path.parent.name + '/' + path.stem, mininterval=3, ascii=True):
261
+ record = dataset.record(index)
262
+ errors = [error.message for error in schema_validator.iter_errors(record)]
263
+ errors += validate_record(record, root)
264
+ if record['dataset'] != path.parent.name or record['split'] != path.stem:
265
+ errors.append('split_or_dataset_mismatch')
266
+ image_key = (record['dataset'], record['split'], record['image_id'])
267
+ if image_key in image_ids:
268
+ errors.append('duplicate_image_id')
269
+ image_ids.add(image_key)
270
+ key = (record['dataset'], Path(record['image_path']).name)
271
+ if key in paths:
272
+ summary['duplicate_image_paths_across_splits'].append([paths[key], record['image_path']])
273
+ paths[key] = record['image_path']
274
+ if record['dataset'] == 'PartImageNet':
275
+ if source_coco is None:
276
+ from pycocotools.coco import COCO
277
+ source_coco = COCO(str(project_path(root, record['source_path'])))
278
+ source_annotations = {ann['id']: ann for ann in source_coco.imgToAnns[int(record['image_id'])]}
279
+ converted_ids = {entry['source_annotation_id'] for entry in record['nodes'] if entry['kind'] == 'part'}
280
+ if converted_ids != set(source_annotations):
281
+ errors.append('source_annotation_id_coverage_mismatch')
282
+ for entry in record['nodes']:
283
+ if entry['kind'] == 'part':
284
+ ann = source_annotations[entry['source_annotation_id']]
285
+ expected, mask_status = source_mask(source_coco, ann)
286
+ if entry['source_label_id'] != ann['category_id']:
287
+ errors.append('source_category_id_not_preserved:' + entry['id'])
288
+ if entry.get('source_segmentation') != ann['segmentation']:
289
+ errors.append('raw_source_geometry_not_preserved:' + entry['id'])
290
+ if mask_status != 'valid':
291
+ summary['source_geometry_issues'].append({'split': record['split'], 'image_id': record['image_id'], 'annotation_id': ann['id'], 'status': mask_status})
292
+ if not np.array_equal(decode_mask(entry['mask']), expected):
293
+ errors.append('source_coco_mask_not_lossless:' + entry['id'])
294
+ stats['images'] += 1
295
+ stats['valid_images'] += not errors
296
+ stats['issues'] += len(errors)
297
+ if errors:
298
+ summary['issues'].append({'dataset': record['dataset'], 'split': record['split'],
299
+ 'image_id': record['image_id'], 'errors': errors})
300
+ summary['splits'][path.parent.name + '/' + path.stem] = dict(stats)
301
+ summary['conversion_integrity_passed'] = not any(any(not error.startswith('missing_image:') for error in issue['errors']) for issue in summary['issues']) and not summary['duplicate_image_paths_across_splits']
302
+ summary['passed'] = not summary['issues'] and not summary['source_geometry_issues'] and not summary['duplicate_image_paths_across_splits']
303
+ target = root / 'results/preparation/validation_report.json'
304
+ target.parent.mkdir(parents=True, exist_ok=True)
305
+ target.write_text(json.dumps(summary, indent=2) + '\n', encoding='utf-8')
306
+ return summary
307
+
308
+
309
+ def visualize(root, annotation_path, index, output):
310
+ sample = UnifiedDataset(annotation_path, root)[index]
311
+ image = sample['image']
312
+ record = sample['record']
313
+ panels = [image.copy()]
314
+ colors = [(230, 90, 60), (40, 170, 180), (210, 180, 30), (120, 100, 200), (70, 180, 80)]
315
+ for kind in ('whole', 'part'):
316
+ array = np.array(image).astype(float)
317
+ for position, entry in enumerate(record['nodes']):
318
+ if entry['kind'] == kind:
319
+ mask = sample['masks'].get(entry['id'])
320
+ if mask is None:
321
+ continue
322
+ array[mask] = 0.45 * array[mask] + 0.55 * np.array(colors[position % len(colors)])
323
+ panels.append(Image.fromarray(array.astype(np.uint8)))
324
+ canvas = Image.new('RGB', (image.width * 3, image.height + 30), 'white')
325
+ draw = ImageDraw.Draw(canvas)
326
+ for position, (panel, title) in enumerate(zip(panels, ('Image', 'Whole groups', 'Part groups'))):
327
+ canvas.paste(panel, (position * image.width, 30))
328
+ draw.text((position * image.width + 8, 8), title, fill='black')
329
+ output.parent.mkdir(parents=True, exist_ok=True)
330
+ canvas.save(output)
331
+
332
+
333
+ def main():
334
+ parser = argparse.ArgumentParser(description=__doc__)
335
+ parser.add_argument('command', choices=['convert', 'validate', 'visualize'])
336
+ parser.add_argument('--root', type=Path, default=ROOT)
337
+ parser.add_argument('--annotations', type=Path)
338
+ parser.add_argument('--index', type=int, default=0)
339
+ parser.add_argument('--output', type=Path)
340
+ args = parser.parse_args()
341
+ if args.command == 'convert':
342
+ print(json.dumps(convert(args.root.resolve()), indent=2))
343
+ elif args.command == 'validate':
344
+ report = validate(args.root.resolve())
345
+ print(json.dumps(report, indent=2))
346
+ raise SystemExit(0 if report['passed'] else 1)
347
+ else:
348
+ if args.annotations is None or args.output is None:
349
+ parser.error('visualize requires --annotations and --output')
350
+ visualize(args.root.resolve(), args.annotations, args.index, args.output)
351
+
352
+
353
+ if __name__ == '__main__':
354
+ main()
code/tools/prepare_data.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extract the supplied archives without changing their original split layout."""
2
+ import argparse
3
+ import json
4
+ import os
5
+ from pathlib import Path, PurePosixPath
6
+ import shutil
7
+ import tempfile
8
+ import zipfile
9
+ from tqdm import tqdm
10
+
11
+ ROOT = Path(__file__).resolve().parents[2]
12
+
13
+
14
+ def extract(archive, target, strip=None):
15
+ count = 0
16
+ for item in tqdm(archive.infolist(), desc=target.name, mininterval=3, ascii=True):
17
+ path = PurePosixPath(item.filename)
18
+ if '__MACOSX' in path.parts or path.name in {'.DS_Store', 'Thumbs.db'} or path.name.startswith('._') or item.is_dir():
19
+ continue
20
+ if path.is_absolute() or '..' in path.parts or '\\' in item.filename:
21
+ raise ValueError(f'Unsafe archive member: {item.filename}')
22
+ parts = path.parts
23
+ if strip and parts[0] == strip:
24
+ parts = parts[1:]
25
+ out = target.joinpath(*parts).resolve()
26
+ if not out.is_relative_to(target.resolve()):
27
+ raise ValueError(f'Archive member escapes destination: {item.filename}')
28
+ if out.exists():
29
+ if out.stat().st_size != item.file_size:
30
+ raise FileExistsError(out)
31
+ else:
32
+ out.parent.mkdir(parents=True, exist_ok=True)
33
+ with archive.open(item) as src, out.open('xb') as dst:
34
+ shutil.copyfileobj(src, dst)
35
+ count += 1
36
+ return count
37
+
38
+
39
+ def main():
40
+ parser = argparse.ArgumentParser(description=__doc__)
41
+ parser.add_argument('--root', type=Path, default=ROOT)
42
+ args = parser.parse_args()
43
+ root = args.root.resolve()
44
+ data = root / 'datasets/PartImageNet'
45
+ report = {}
46
+ with zipfile.ZipFile(root / 'datasets/archives/PartImageNet_OOD.zip') as outer:
47
+ (data / 'annotations').mkdir(parents=True, exist_ok=True)
48
+ for split in ('train', 'val', 'test'):
49
+ payload = outer.read(split + '.json')
50
+ (data / 'annotations' / (split + '.json')).write_bytes(payload)
51
+ with tempfile.TemporaryDirectory(prefix='partimagenet-') as tmp:
52
+ nested = Path(tmp) / (split + '.zip')
53
+ with outer.open(split + '.zip') as src, nested.open('wb') as dst:
54
+ shutil.copyfileobj(src, dst)
55
+ with zipfile.ZipFile(nested) as archive:
56
+ count = extract(archive, data / 'images' / split, strip=split)
57
+ annotation = json.loads(payload)
58
+ image_root = data / 'images' / split
59
+ missing = [im['file_name'] for im in annotation['images']
60
+ if not (image_root / im['file_name'][:9] / im['file_name']).is_file()]
61
+ if missing:
62
+ print(f'INCOMPLETE SOURCE ARCHIVE: {split}: {missing}')
63
+ report['PartImageNet/' + split] = {'images': len(annotation['images']),
64
+ 'annotations': len(annotation['annotations']), 'extracted_files': count,
65
+ 'missing_images': len(missing), 'missing_filenames': missing}
66
+ with zipfile.ZipFile(root / 'datasets/archives/Pascal_Part.zip') as archive:
67
+ extract(archive, root / 'datasets/Pascal-Part', strip='Pascal_Part')
68
+ for split in ('train', 'val'):
69
+ base = root / 'datasets/Pascal-Part'
70
+ parts = sorted((base / 'annotations' / split).glob('*.png'))
71
+ images = {p.stem: p for p in (base / 'JPEGImages' / split).iterdir() if p.is_file()}
72
+ for part in parts:
73
+ if part.stem not in images or not (base / 'annotations' / (split + '_whole') / part.name).is_file():
74
+ raise FileNotFoundError(part)
75
+ report['Pascal-Part/' + split] = {'images': len(images), 'part_masks': len(parts),
76
+ 'whole_masks': len(list((base / 'annotations' / (split + '_whole')).glob('*.png')))}
77
+ output = root / 'results/preparation'
78
+ output.mkdir(parents=True, exist_ok=True)
79
+ (output / 'data_inventory.json').write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
80
+ print(json.dumps(report, indent=2))
81
+
82
+
83
+ if __name__ == '__main__':
84
+ main()
85
+
datasets/PartImageNet/images/test/n01494475/n01494475_742.JPEG ADDED

Git LFS Details

  • SHA256: b0f975b523f75d6511e930acb50a7571cd2c2572af128b40534e44a060ca29f8
  • Pointer size: 131 Bytes
  • Size of remote file: 109 kB
datasets/archives/PartImageNet_OOD.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56de44826ab800e49f99d36ca9c1412e6e406e5d337100f01f4783e1e40aed35
3
+ size 2910755506
datasets/archives/Pascal_Part.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a07a8375617ee29947cee3ba2b500623b58b4d320ddaff03cb266eb874678e6
3
+ size 1149438894
datasets/archives/Pascal_Part_original_trainval.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e8e3a4b0b59ed54483081649de4de92c01ee4e5e8dd825a0cc36ae2e8b84732
3
+ size 80872607
datasets/release/package_report.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "passed": true,
3
+ "package": "unified_partwhole_v1.zip",
4
+ "bytes": 71593420,
5
+ "sha256": "754dc4752761f502afdd88ff97f61849a8257a3b364a5b6acddfda9feae26edf",
6
+ "verified_payload_files": 25,
7
+ "zip_entries": 26,
8
+ "image_records": 33520,
9
+ "verification": "Every payload file read back with ZIP CRC verification and SHA256 equality; embedded manifest equals source."
10
+ }
datasets/release/unified_partwhole_v1.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:754dc4752761f502afdd88ff97f61849a8257a3b364a5b6acddfda9feae26edf
3
+ size 71593420
docs/UNIFIED_SCHEMA.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Unified part-whole annotation v1
2
+
3
+ Each JSONL line describes one image. Paths are relative to the project root; moving the entire project does not require rewriting annotations. `schema.json` is the machine-readable record contract.
4
+
5
+ Required record fields: `schema_version`, `dataset`, `split`, `image_id`, `image_path`, `image_available`, `width`, `height`, `source_path`, `hierarchy_semantics`, and `nodes`.
6
+
7
+ Each node contains a unique image-local `id`, optional `parent_id`, `level`, `kind` (`whole` or `part`), dataset-namespaced `category`, `source_label_id`, `provenance`, raster `area`, and a COCO compressed RLE `mask` (`size: [height,width]`, ASCII `counts`). Original image IDs and split assignments are preserved. Numeric class IDs are never compared across datasets without an explicit mapping.
8
+
9
+ ## PartImageNet
10
+
11
+ A part node corresponds to one original COCO annotation. Its original annotation ID and segmentation geometry are retained. Whole nodes are unions of decoded masks sharing a source supercategory; this derivation is identified by provenance. Category grouping does not manufacture object instance IDs or additional anatomical levels.
12
+
13
+ `mask_status` distinguishes valid geometry from invalid or partly invalid source geometry. Fewer than three polygon vertices cannot define an area. Such components are retained as raw geometry, flagged, and excluded from rasterization; valid components are still preserved. An all-invalid polygon has an empty placeholder raster, which is never exposed as a usable part mask by `UnifiedDataset.__getitem__`. The original polygon remains in `record()` for inspection. The checker reports these source defects separately from conversion errors.
14
+
15
+ ## Pascal-Part
16
+
17
+ The supplied data contains integer part PNGs and integer whole PNGs, without a category-name or ignore-label table. All numerical values are retained. Whole nodes represent each whole-label region; part nodes represent each nonempty intersection of a part label with a whole label. Thus a single semantic part label can appear below more than one parent without guessing which pixels belong to an instance.
18
+
19
+ Both source rasters can be recovered exactly: assign each whole node's source_label_id to its mask, and do the same for part nodes. Validation requires pixel equality and exactly one covering node at each raster level. No background label is silently removed. Naming labels or excluding background for training requires an authoritative mapping; the converter does not invent one.
20
+
21
+ ## Shared loader
22
+
23
+ ```python
24
+ from pathlib import Path
25
+ from torch.utils.data import DataLoader
26
+ from partwhole import UnifiedDataset
27
+
28
+ root = Path(r'D:\Projects\Computer_Vision_Project')
29
+ dataset = UnifiedDataset(root / 'datasets/unified/PartImageNet/val.jsonl', root)
30
+ sample = dataset[0]
31
+ # sample: record, RGB PIL image, valid masks keyed by node ID, invalid_node_ids
32
+ loader = DataLoader(dataset, batch_size=2, collate_fn=list, num_workers=0)
33
+ ```
34
+
35
+ Images are read with EXIF orientation applied, matching the annotation coordinate dimensions. Original image bytes are preserved. Six PartImageNet images require this orientation handling.
36
+
37
+ `record(index)` reads metadata without loading images or masks. `dataset[index]` fails visibly if the image is missing; it does not silently skip the record. Variable image sizes and node counts are kept as a list in DataLoader. This is a data-loading API, not a finalized training target or tokenizer.
38
+
39
+ ## Validation and quality report
40
+
41
+ Validation checks the JSON schema, safe file references, image and mask dimensions, image/node ID uniqueness, parent references, root/child roles, levels, cycles, mask areas, part containment, split identity, original annotation coverage and categories, COCO mask equivalence for decodable geometry, raw geometry retention, and exact Pascal raster reconstruction.
42
+
43
+ `conversion_integrity_passed` reports conversion consistency. `passed` additionally requires no missing images, no source geometry defects, and no duplicate image paths across splits. Unresolved source issues remain visible and produce a nonzero strict validation exit code. Empty source masks are counted in the conversion summary; they are not replaced with invented content.
44
+
45
+
46
+ ## Source-backed Pascal metadata (2026-11-01)
47
+
48
+ The supplied PNG archive itself has no name table. A sidecar table has now been reconstructed from the original author-verified named MAT archive and checked against all 9,425 current images. categories.json adds display_name and is_background without changing numeric category keys or JSONL masks. Background is whole=16, part=54; no ignore code occurs in the processed PNGs. See docs/data/PASCAL_LABELS.md and datasets/unified/Pascal-Part/label_metadata.json.
49
+
50
+ Raster containment is distinct from semantic parent correctness. The named audit identifies source PNG class conflicts in 512 train and 547 val images; those intersections remain preserved and are flagged in results/preparation/pascal_semantic_quality.json. Do not interpret conversion_integrity_passed as a claim that every source semantic relation is correct. No source pixels were repaired or relabelled.
docs/data/ADDITIONAL_DATASET_SCOPE.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Additional dataset scope
2
+
3
+ Current local release: PartImageNet OOD and the supplied Compositor-style Pascal-Part subset. These are the two converted, validated sources. This scope describes the release contents; it does not remove the proposal's additional-dataset commitment.
4
+
5
+ ## Next source: PACO-LVIS
6
+
7
+ Use PACO-LVIS as the next planned extension, rather than counting a Pascal-derived person subset as an independent source. Its official annotations contain object and part masks plus obj_ann_id links, providing instance-level part/whole relations beyond the current semantic groupings. Retain image IDs, original splits, category namespaces, annotation IDs, masks and exhaustive/negative-category metadata. Do not discard these fields or derive parent identity merely by overlap.
8
+
9
+ Official resources:
10
+
11
+ - https://github.com/facebookresearch/paco
12
+ - https://github.com/facebookresearch/paco/blob/main/docs/PACO_DATASET.md
13
+
14
+ Integration acceptance criteria: resolve the documented annotation version and source images; preserve explicit object links and mask geometry; identify void/negative/non-exhaustive semantics; validate split disjointness and every parent reference; extend the shared loader without fabricating missing masks; publish source-specific counts and license records. An annotation-only preview must be labelled as such and cannot be counted as a complete image dataset.
15
+
16
+ PACO-EGO4D is outside the immediate extension because video access and temporal instances add requirements not needed to demonstrate a third image source. PACO has not been downloaded, converted, or benchmarked in this release. The extra-dataset implementation task remains open. The official repository's software license is not automatically a blanket license for underlying COCO/LVIS/Ego4D images.
docs/data/DATASET_CARD.md ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Unified part-whole dataset card
2
+
3
+ Version: 1.0-source-backed, local course release, 2026-11-01.
4
+
5
+ ## Contents and intended use
6
+
7
+ The release standardizes PartImageNet OOD and the supplied Compositor-style Pascal-Part processed subset into one image-record format with compressed RLE masks and explicit parent references. It supports inspecting source annotations, shared loading, conversion checks and hierarchical-model evaluation. It does not supply a trained Seq2Seq tree model, an instance annotation for semantic-only regions, or a task-specific training target.
8
+
9
+ | Source / split | Images | Whole nodes | Part nodes | Invalid part geometry |
10
+ | --- | ---: | ---: | ---: | ---: |
11
+ | PartImageNet train | 16,540 | 16,523 | 76,483 | 121 |
12
+ | PartImageNet val | 2,957 | 2,954 | 13,371 | 17 |
13
+ | PartImageNet test | 4,598 | 4,590 | 22,106 | 30 |
14
+ | Pascal-Part train | 4,653 | 10,740 | 28,953 | 0 |
15
+ | Pascal-Part val | 4,772 | 10,942 | 29,584 | 0 |
16
+ | Total | 33,520 | 45,749 | 170,497 | 168 |
17
+
18
+ Source: datasets/unified/conversion_summary.json. Node counts include preserved source background/empty regions where applicable; they are not object instance counts. The original Pascal-Part dataset has 10,103 train/val images; this supplied processed subset contains 9,425 and must not be presented as the full original dataset.
19
+
20
+ ## Schema and semantic scope
21
+
22
+ Each JSONL line stores dataset/split/image ID, relative image/source paths, dimensions and nodes. Each node has an image-local ID, parent_id, whole/part kind, level, dataset-namespaced category, original label ID, provenance, area and compressed COCO RLE. PartImageNet also retains raw segmentation geometry and annotation ID. Paths resolve from the project/package root; numeric IDs never cross dataset namespaces implicitly.
23
+
24
+ PartImageNet whole nodes are unions of decodable part regions sharing a supercategory, not inferred object instances. Pascal whole/part nodes preserve numerical PNG values through pixel intersections, allowing exact reconstruction of both processed rasters. This is a common two-level semantic representation, not a complete anatomical hierarchy.
25
+
26
+ PartImageNet has 11 whole supercategories and 40 part categories. Pascal metadata adds source-backed display names for 16 foreground whole categories and 54 foreground part groups, plus background. Display names were reconstructed from verified original named MATs using all 9,425 current image IDs. Original numeric category keys remain unchanged. See PASCAL_LABELS.md and datasets/unified/Pascal-Part/label_metadata.json for exact evidence and ambiguous components.
27
+
28
+ ## Quality and consumer policy
29
+
30
+ All 33,520 records passed conversion integrity checks with zero conversion issues and no split filename duplication. The 168 original malformed polygons remain represented and flagged. A valid-but-empty test annotation is counted separately. Default loader masks omit non-valid mask_status, while record() exposes all original geometry and flags. See QUALITY_POLICY.md.
31
+
32
+ A subsequent source-backed semantic audit found foreground-part/whole class conflicts in the supplied Pascal PNGs: 512/4,653 train images (871,870 pixels; 0.4016% of foreground-part pixels), 547/4,772 val images (706,599 pixels; 0.3143%). There are also part-unlabelled pixels within foreground objects. These are properties of the supplied processed labels, not raster loss introduced by conversion. Preserve the source rasters and consult results/preparation/pascal_semantic_quality.json before defining semantic supervision. Filtering must be explicit; do not treat every preserved intersection as a semantically verified parent link.
33
+
34
+ For PartImageNet val evaluation, all 2,957 images remain, 17 invalid masks affecting 16 images are excluded, and uncovered pixels remain background. This policy is specific to that recorded experiment, not an automatic training rule for every consumer.
35
+
36
+ ## Loading and visualization
37
+
38
+ From the project root with the project venv:
39
+
40
+ ```powershell
41
+ & .\venv\Scripts\python.exe .\code\examples\read_unified.py --dataset Pascal-Part --split val --index 0
42
+ & .\venv\Scripts\python.exe .\code\examples\read_unified.py --dataset PartImageNet --split val --index 0 --output .\results\data_delivery\partimagenet_example.png
43
+ ```
44
+
45
+ The example reads metadata without source images unless --output is requested. For full loading use UnifiedDataset[index]; for DataLoader use collate_fn=list because image shapes and node counts vary. Category names come from categories.json; is_background is explicit for Pascal. The example also prints foreground_candidate_node_ids after explicit background, invalid/empty-mask and semantic-parent filtering, plus semantic_conflict_node_ids. These are consumer candidates, not rewritten dataset nodes. The optional preview still shows all preserved source groups.
46
+
47
+ Source images are not included in the annotation-only review ZIP. Obtain the original sources, retain their prescribed splits and place them at datasets/PartImageNet/images/<split>/<synset>/ and datasets/Pascal-Part/JPEGImages/<split>/. The original project loader's required libraries are NumPy, Pillow, pycocotools and tqdm; conversion/validation additionally uses the installed project dependencies. A mask or record can be inspected without a model checkpoint.
48
+
49
+ ## Provenance, packaging and remaining scope
50
+
51
+ SOURCES_AND_LICENSES.md records original URLs, revisions, archive hashes and source-specific terms. This local annotation-only ZIP includes converted JSONL, schema, category metadata, quality reports, examples and a SHA256 manifest. It excludes images, model weights, raw archives and venv. It does not assign a new project-wide license.
52
+
53
+ PACO-LVIS is the planned additional image source because it offers explicit object-instance links and masks. It is not yet downloaded or converted. This release has two data sources; ADDITIONAL_DATASET_SCOPE.md records the third-source acceptance criteria without presenting it as completed.
54
+
docs/data/PASCAL_LABELS.md ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pascal-Part source-backed label table
2
+
3
+ Derived from the original named MAT archive, whose MD5 matches the author page. All 9,425 current images were compared. Whole-name mappings are pixel-pure after retaining the 16 part-labelled classes. Each of 54 foreground part groups has unambiguous same-class source components in both train and val. Display names summarize these components; the exact publisher label table was not released. Numeric IDs, PNGs, JSONL category keys and masks are unchanged.
4
+
5
+ Background: whole=16, part=54. Part background can occur inside a foreground object with no part annotation. No ignore code is observed; in particular, do not assign 0 or 255 as background/ignore by convention. Source MAT overlays are not claimed to reproduce the processed part PNGs exactly. Four ambiguous original tokens are preserved with counts in label_metadata.json; processed-PNG semantic-parent conflicts are separately reported in pascal_semantic_quality.json.
6
+
7
+ | Part ID | Display name | Expected whole ID |
8
+ | ---: | --- | ---: |
9
+ | 0 | aeroplane/body | 0 |
10
+ | 1 | aeroplane/engine | 0 |
11
+ | 2 | aeroplane/wing | 0 |
12
+ | 3 | aeroplane/stern | 0 |
13
+ | 4 | aeroplane/tail | 0 |
14
+ | 5 | aeroplane/wheel | 0 |
15
+ | 6 | bicycle/wheel and chainwheel | 1 |
16
+ | 7 | bicycle/handlebar and headlight | 1 |
17
+ | 8 | bicycle/saddle | 1 |
18
+ | 9 | bird/head | 2 |
19
+ | 10 | bird/leg and foot | 2 |
20
+ | 11 | bird/wing | 2 |
21
+ | 12 | bird/tail | 2 |
22
+ | 13 | bird/torso and neck | 2 |
23
+ | 14 | bottle/body | 3 |
24
+ | 15 | bottle/cap | 3 |
25
+ | 16 | bus/body | 4 |
26
+ | 17 | bus/wheel | 4 |
27
+ | 18 | bus/mirror | 4 |
28
+ | 19 | car/body | 5 |
29
+ | 20 | car/wheel | 5 |
30
+ | 21 | car/mirror | 5 |
31
+ | 22 | cat/head | 6 |
32
+ | 23 | cat/leg and paw | 6 |
33
+ | 24 | cat/tail | 6 |
34
+ | 25 | cat/torso and neck | 6 |
35
+ | 26 | cow/head | 7 |
36
+ | 27 | cow/leg | 7 |
37
+ | 28 | cow/tail | 7 |
38
+ | 29 | cow/torso and neck | 7 |
39
+ | 30 | dog/head | 8 |
40
+ | 31 | dog/leg and paw | 8 |
41
+ | 32 | dog/tail | 8 |
42
+ | 33 | dog/torso and neck | 8 |
43
+ | 34 | horse/head | 9 |
44
+ | 35 | horse/leg and hoof | 9 |
45
+ | 36 | horse/tail | 9 |
46
+ | 37 | horse/torso and neck | 9 |
47
+ | 38 | motorbike/wheel | 10 |
48
+ | 39 | motorbike/handlebar and headlight | 10 |
49
+ | 40 | motorbike/saddle | 10 |
50
+ | 41 | person/head | 11 |
51
+ | 42 | person/leg and foot | 11 |
52
+ | 43 | person/arm and hand | 11 |
53
+ | 44 | person/torso and neck | 11 |
54
+ | 45 | pottedplant/plant | 12 |
55
+ | 46 | pottedplant/pot | 12 |
56
+ | 47 | sheep/head | 13 |
57
+ | 48 | sheep/leg | 13 |
58
+ | 49 | sheep/tail | 13 |
59
+ | 50 | sheep/torso and neck | 13 |
60
+ | 51 | train/coach | 14 |
61
+ | 52 | train/locomotive | 14 |
62
+ | 53 | tvmonitor/screen | 15 |
63
+ | 54 | Background / unlabelled part | - |
64
+
65
+ Whole IDs: 0=aeroplane, 1=bicycle, 2=bird, 3=bottle, 4=bus, 5=car, 6=cat, 7=cow, 8=dog, 9=horse, 10=motorbike, 11=person, 12=pottedplant, 13=sheep, 14=train, 15=tvmonitor, 16=Background.
66
+
67
+ Evidence: results/preparation/pascal_original_crosswalk.json, pascal_crosswalk_counts.npz and pascal_semantic_quality.json. Rebuild the original-name crosswalk with code/tools/build_pascal_metadata.py, then run code/tools/finalize_pascal_labels.py. The source archive is datasets/archives/Pascal_Part_original_trainval.tar.gz.
68
+
docs/data/QUALITY_POLICY.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Source geometry and background policy
2
+
3
+ Converted records retain every original annotation and raw polygon. Non-decodable geometry receives mask_status and an empty placeholder; partially decodable geometry retains its valid raster components and raw geometry but is not exposed as a usable part mask by the shared loader. Never replace an invalid polygon with a guessed box or silently drop its record.
4
+
5
+ Across PartImageNet: 168 invalid-geometry annotations (train 121, val 17, test 30). A separate valid-but-empty source mask is counted in the test conversion summary; it is not an additional malformed polygon. Whole masks are derived unions, so empty source content may produce empty whole nodes too. These categories must not be conflated.
6
+
7
+ Default loader: exclude mask_status other than valid from sample['masks']; retain the node in sample['record'] and list it in invalid_node_ids. A valid empty mask remains represented as source data. Training consumers must explicitly define any further filtering or loss mask; this package does not silently infer a supervision objective.
8
+
9
+ Current PartImageNet validation experiment: exclude the 17 invalid masks, retain all 2,957 images, and keep uncovered pixels at background. This affects 16 images. There is no ignore mask or image-level exclusion. This choice follows the released loader convention and is recorded with every affected image; it is not a claim that malformed regions were recovered.
10
+
11
+ Pascal source PNGs retain all values. Verified named metadata is a sidecar lookup, not a rewrite of masks, category keys or splits. Background IDs and observed-label scope are documented with the source-backed label table. No new ignore ID is manufactured for absent labels.
12
+
13
+ Validation distinguishes conversion integrity from source quality. The final report has conversion_integrity_passed=true and zero conversion issues; strict passed=false reflects preserved source defects. A nonzero strict validator exit in this state is expected and must not be hidden or changed to pass.
14
+
15
+ Source-backed Pascal metadata now confirms whole background=16 and part background=54, with no observed ignore code. A semantic-parent diagnostic flags 871,870 train and 706,599 val foreground-part pixels whose expected whole class differs from the supplied whole PNG. It affects 512 train and 547 val images. This diagnostic does not rewrite the original rasters or their lossless converted intersections. A consumer defining semantic targets should explicitly exclude or separately handle these nodes. Part-background pixels inside a foreground whole are recorded separately and are not counted as a foreground semantic-class conflict.
docs/data/SOURCES_AND_LICENSES.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Source and license record
2
+
3
+ This local package preserves provenance by source. It does not assign a new blanket license to third-party images or annotations.
4
+
5
+ | Component | Exact source / version | Stated license or terms |
6
+ | --- | --- | --- |
7
+ | PartImageNet OOD | turkeyju/PartImageNet HF revision cfa2edf3cf5ffbede2bd1fc934edca0aba99f042; PartImageNet_OOD.zip | HF dataset metadata states Apache-2.0. ImageNet-origin images retain their source conditions; the repository label alone does not establish all image rights. |
8
+ | Pascal-Part processed PNGs | Same HF revision, Pascal_Part.zip SHA256 5a07a8375617ee29947cee3ba2b500623b58b4d320ddaff03cb266eb874678e6 | Processed format matches the author's Compositor DATASETS.md. No separate Pascal image/annotation license table was included in the archive. |
9
+ | Original Pascal-Part named MATs | https://roozbehm.info/pascal-parts/trainval.tar.gz; official MD5 2fa0a19ee9b5e43b2bee520166111120; SHA256 8e8e3a4b0b59ed54483081649de4de92c01ee4e5e8dd825a0cc36ae2e8b84732 | Consulted original dataset page provides annotations and refers users to VOC2010 for images; no standalone reuse license is stated there. Original image terms remain separate. |
10
+ | CAST code | twke18/CAST commit ec85adff6fae5802684e21423112cab55fc732ae | MIT; retained at code/CAST/LICENSE. |
11
+ | DAVIS metric code | davisvideochallenge/davis2017-evaluation commit ac7c43fca936f9722837b7fbd337d284ba37004b | BSD-3-Clause; exact source and LICENSE retained in code/third_party/davis2017. |
12
+ | Compositor reference | TACJu/Compositor commit 30e6f1ac15aa52936b9a59fe46c0dae1deff6436; DATASETS.md; CVPR2023 paper | Repository software: Apache-2.0. Used for provenance and preprocessing scope; not a new license for VOC images. |
13
+ | Project converters, loader and report | This project, authors Rafid Ahmed and Wugeng Zheng | No project-wide software license has been selected. Do not present third-party licenses as a license granted by the project authors. |
14
+
15
+ Official source links:
16
+
17
+ - https://huggingface.co/datasets/turkeyju/PartImageNet/raw/cfa2edf3cf5ffbede2bd1fc934edca0aba99f042/README.md
18
+ - https://github.com/TACJu/PartImageNet
19
+ - https://roozbehm.info/pascal-parts/pascal-parts.html
20
+ - https://github.com/TACJu/Compositor/blob/30e6f1ac15aa52936b9a59fe46c0dae1deff6436/DATASETS.md
21
+
22
+ The annotation-only review bundle excludes source images, weights, venv and raw source archives. Its source-specific notices and hashes accompany the converted annotations. This is a local course deliverable, not an assertion of unrestricted public redistribution permission.
results/data_delivery/partimagenet_example.png ADDED

Git LFS Details

  • SHA256: bfc597adaa7c86a6b12e284562d6db7dac931469eac7655e57fe34af625f8a84
  • Pointer size: 131 Bytes
  • Size of remote file: 574 kB
results/data_delivery/pascal_example.png ADDED

Git LFS Details

  • SHA256: d7a434ccc126b580702926528cfdfe8819f27368c80918f2c41a586a41b4184b
  • Pointer size: 131 Bytes
  • Size of remote file: 554 kB
results/preparation/recovered_image.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image": "D:\\Projects\\Computer_Vision_Project\\datasets\\PartImageNet\\images\\test\\n01494475\\n01494475_742.JPEG",
3
+ "source_archive": "https://huggingface.co/datasets/turkeyju/PartImageNet/resolve/cfa2edf3cf5ffbede2bd1fc934edca0aba99f042/PartImageNet_Seg.zip",
4
+ "bytes": 109104,
5
+ "dimensions": [
6
+ 500,
7
+ 375
8
+ ],
9
+ "sha256": "b0f975b523f75d6511e930acb50a7571cd2c2572af128b40534e44a060ca29f8"
10
+ }