RefSeg-CA / source /code /prepare_official_masks.py
nmsofficial's picture
Add verified public availability and human-evaluation guide
9126e0d verified
Raw History Blame Contribute Delete
1.34 kB
"""Reproduce ReLA's 480x480 polygon-transform evaluation targets."""
from pathlib import Path
import json,copy
import numpy as np
from PIL import Image
from pycocotools import mask as cm
ROOT=Path(__file__).resolve().parents[1];from project_paths import legacy_root;OLD=legacy_root(ROOT)
refs=json.loads((OLD/'assets/grefcoco/grefs(unc).json').read_text())
coco=json.loads((OLD/'assets/grefcoco/instances.json').read_text());ims={x['id']:x for x in coco['images']};anns={x['id']:x for x in coco['annotations']}
dest=ROOT/'data/natural/masks_official480';dest.mkdir(parents=True,exist_ok=True)
n=0
for r in refs:
if r['split'] not in ('val','testA','testB'):continue
gt=np.zeros((480,480),bool);im=ims[r['image_id']]
if not r['no_target']:
for aid in r['ann_id']:
if anns[aid].get('iscrowd',0):continue
seg=anns[aid]['segmentation'];assert isinstance(seg,list),'Official mapper expects polygons'
polys=[]
for polygon in seg:
p=np.asarray(polygon,float).reshape(-1,2);p[:,0]*=480/im['width'];p[:,1]*=480/im['height'];polys.append(p.ravel().tolist())
z=cm.decode(cm.frPyObjects(polys,480,480));gt|=z.any(axis=2)
Image.fromarray(gt.astype('uint8')*255).save(dest/f"ref_{r['ref_id']}.png");n+=1
print('OFFICIAL_MASKS_COMPLETE',n,flush=True)