RefSeg-CA / source /code /prepare_full_natural.py
nmsofficial's picture
Add verified public availability and human-evaluation guide
9126e0d verified
Raw History Blame Contribute Delete
4.39 kB
"""Prepare every official gRefCOCO evaluation expression, without subsampling."""
from pathlib import Path
import json, hashlib, collections, concurrent.futures, urllib.request, time, os
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)
def main():
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']}
chosen=[r for r in refs if r['split'] in ('val','testA','testB')]
idir=ROOT/'data/natural/images';mdir=ROOT/'data/natural/masks'
idir.mkdir(parents=True,exist_ok=True);mdir.mkdir(parents=True,exist_ok=True)
image_ids=sorted({r['image_id'] for r in chosen})
def fetch(i):
name=ims[i]['file_name']; out=idir/name
if out.exists():return i,'cached'
candidates=[OLD/'data/natural/images'/name,OLD/'data/natural/images'/f'{i:012d}.jpg']
for p in candidates:
if p.exists():out.symlink_to(p);return i,'reused'
url='https://s3.amazonaws.com/images.cocodataset.org/train2014/'+name
for attempt in range(4):
try:
with urllib.request.urlopen(url,timeout=90) as response:blob=response.read()
tmp=out.with_suffix('.partial');tmp.write_bytes(blob)
with Image.open(tmp) as image:image.verify()
tmp.replace(out);return i,'downloaded'
except Exception:
if attempt==3:raise
time.sleep(2**attempt)
counts=collections.Counter()
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
for k,(iid,state) in enumerate(pool.map(fetch,image_ids)):
counts[state]+=1
if k%100==0:print('IMAGES',k,len(image_ids),dict(counts),flush=True)
rows=[]; strata=collections.Counter()
for r in chosen:
im=ims[r['image_id']];h,w=im['height'],im['width']; gt=np.zeros((h,w),bool)
aids=[] if r['no_target'] else r['ann_id']
if not isinstance(aids,list):aids=[aids]
for aid in aids:
seg=anns[aid]['segmentation']
if isinstance(seg,list):z=cm.decode(cm.frPyObjects(seg,h,w))
elif isinstance(seg['counts'],list):z=cm.decode(cm.frPyObjects(seg,h,w))
else:z=cm.decode(seg)
gt|=z.any(axis=2) if z.ndim==3 else z.astype(bool)
assert bool(gt.any())==bool(aids),(r['ref_id'],aids)
gp=mdir/f"ref_{r['ref_id']}.png";Image.fromarray(gt.astype('uint8')*255).save(gp)
for sentence in r['sentences']:
row=dict(id=f"gref_{r['ref_id']}_{sentence['sent_id']}",scene_id=f"coco_{r['image_id']}",image_id=r['image_id'],ref_id=r['ref_id'],sent_id=sentence['sent_id'],domain='natural_full',split=r['split'],mode='zero' if not aids else 'one' if len(aids)==1 else 'multi',target_count=len(aids),query=sentence['raw'],image_path=str((idir/im['file_name']).relative_to(ROOT)),gt_path=str(gp.relative_to(ROOT)),seed=0,corruption='clean',pair_id=None,endpoint=None,template='official')
rows.append(row);strata[(r['split'],row['mode'])]+=1
assert len(rows)==49492 and len({r['id'] for r in rows})==len(rows)
mp=ROOT/'data/natural_full.jsonl';mp.write_text(''.join(json.dumps(r)+'\n' for r in rows))
old_rows=[json.loads(s) for s in (OLD/'data/manifest.jsonl').read_text().splitlines()]
train_ids={int(r['scene_id'].split('_')[-1]) for r in old_rows if r['domain']=='natural' and r['split'] in ('fit','cal')}
overlap=sorted(train_ids&set(image_ids))
meta=dict(expressions=len(rows),references=len(chosen),images=len(image_ids),image_fetch=dict(counts),strata={f'{k[0]}/{k[1]}':v for k,v in strata.items()},manifest_sha256=hashlib.sha256(mp.read_bytes()).hexdigest(),old_calibration_image_overlap=overlap,source='FudanCVL/gRefCOCO; official repository-linked release',source_sha256={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in [OLD/'assets/grefcoco/grefs(unc).json',OLD/'assets/grefcoco/instances.json']},slurm_job_id=os.getenv('SLURM_JOB_ID'))
(ROOT/'protocol/natural_full_manifest.json').write_text(json.dumps(meta,indent=2));print(json.dumps(meta,indent=2),flush=True)
if __name__=='__main__':main()