File size: 3,281 Bytes
0ea7dca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Exact PNG-derived BOP visible/valid metrics, preserving raw writer metadata.

Only derived annotation fields change; RGB, depth, masks, poses and camera K do
not. Full silhouette area/box remain the writer's padded-image measurement,
except the area is bounded below by the saved, clipped amodal-mask area.
"""
import json
from pathlib import Path
import cv2
import numpy as np
from scripts.audit_handal40_render import sha


def canonicalize(root):
    scene=root/'bop_data/handal/train_pbr/000000';path=scene/'scene_gt_info.json'
    if (root/'visible_count_canonicalization.json').exists():
        receipt=json.loads((root/'visible_count_canonicalization.json').read_text())
        if sha(path)!=receipt['canonical_info_sha256']:raise ValueError('previously canonicalized metadata changed')
        return receipt
    raw=path.read_bytes();info=json.loads(raw);changes=[]
    for frame,rows in info.items():
        depth=cv2.imread(str(scene/'depth'/f'{int(frame):06d}.png'),cv2.IMREAD_UNCHANGED)
        if depth is None:raise ValueError('missing depth')
        for i,row in enumerate(rows):
            mask=cv2.imread(str(scene/'mask'/f'{int(frame):06d}_{i:06d}.png'),0)
            vis=cv2.imread(str(scene/'mask_visib'/f'{int(frame):06d}_{i:06d}.png'),0)
            if mask is None or vis is None or mask.shape!=depth.shape or vis.shape!=depth.shape:raise ValueError('mask/depth dimensions')
            if not set(np.unique(mask))<={0,255} or not set(np.unique(vis))<={0,255}:raise ValueError('non-binary mask')
            m=mask>0;v=vis>0
            if np.any(v&~m):raise ValueError('visible pixels outside amodal silhouette')
            visible=int(v.sum());valid=int((m&(depth>0)).sum());all_pixels=max(row['px_count_all'],int(m.sum()))
            if not 0<=visible<=valid<=all_pixels:raise ValueError('invalid BOP pixel count ordering')
            differences=[abs(visible-row['px_count_visib']),abs(valid-row['px_count_valid']),abs(all_pixels-row['px_count_all'])]
            if max(differences)>8:raise ValueError('raster-derived count adjustment exceeds8 pixels; investigate')
            x,y,w,h=cv2.boundingRect(vis)
            bbox=[x,y,w-1,h-1] if visible else [-1,-1,-1,-1]
            after={**row,'px_count_all':all_pixels,'px_count_valid':valid,'px_count_visib':visible,
                   'visib_fract':visible/all_pixels if all_pixels else 0.,'bbox_visib':bbox}
            if after!=row:changes.append({'frame':int(frame),'instance':i,'before':dict(row),'after':after})
            rows[i]=after
    archive=root/'writer_raw';archive.mkdir(exist_ok=True)
    original=archive/'scene_gt_info.json'
    if original.exists() and original.read_bytes()!=raw:raise ValueError('raw writer metadata already differs')
    original.write_bytes(raw)
    path.write_text(json.dumps(info,indent=2)+'\n')
    result={'method':'saved PNG visible/valid counts and visible bbox; full amodal lower bound',
            'max_allowed_pixel_count_correction':8,'raw_info_sha256':sha(original),
            'canonical_info_sha256':sha(path),'implementation_sha256':sha(Path(__file__)),
            'changed_instances':len(changes),'changes':changes}
    (root/'visible_count_canonicalization.json').write_text(json.dumps(result,indent=2)+'\n')
    return result