| """Procedural, paired-render RefSeg-CA scenes with exact visible-instance GT. |
| |
| These are benchmark inputs, not generated illustrations or TikZ drawings. |
| Geometry, visibility and query targets are shared between flat/rich images. |
| """ |
| from pathlib import Path |
| import argparse,json,math,hashlib,collections |
| import numpy as np |
| from PIL import Image,ImageDraw,ImageFilter |
| ROOT=Path(__file__).resolve().parents[1] |
| S=384;AA=2 |
| COLORS={'red':(196,38,56),'blue':(38,87,176),'green':(33,139,91),'yellow':(232,188,35),'purple':(135,64,166),'orange':(223,111,38),'pink':(216,99,150),'brown':(127,83,53),'cyan':(27,160,186),'olive':(117,129,45)} |
| SHAPES=['circle','square','triangle','star','cross','ellipse','capsule','heart','diamond','ring','hexagon'] |
| PLURAL={'ellipse':'ellipses','cross':'crosses','hexagon':'hexagons'} |
| def plural(x):return PLURAL.get(x,x+'s') |
|
|
| def object_mask(shape,size,angle): |
| n=128*AA;m=Image.new('L',(n,n));d=ImageDraw.Draw(m);c=n/2 |
| x0,y0,x1,y1=[v*AA for v in (28,28,100,100)] |
| if shape=='circle':d.ellipse((x0,y0,x1,y1),fill=255) |
| elif shape=='ellipse':d.ellipse((20*AA,37*AA,108*AA,91*AA),fill=255) |
| elif shape=='square':d.rectangle((x0,y0,x1,y1),fill=255) |
| elif shape=='capsule':d.rounded_rectangle((19*AA,40*AA,109*AA,88*AA),radius=24*AA,fill=255) |
| elif shape=='ring': |
| d.ellipse((x0,y0,x1,y1),fill=255);d.ellipse((45*AA,45*AA,83*AA,83*AA),fill=0) |
| elif shape=='cross': |
| d.rectangle((49*AA,24*AA,79*AA,104*AA),fill=255);d.rectangle((24*AA,49*AA,104*AA,79*AA),fill=255) |
| elif shape=='heart': |
| pts=[] |
| for t in np.linspace(0,2*math.pi,200): |
| x=16*math.sin(t)**3;y=13*math.cos(t)-5*math.cos(2*t)-2*math.cos(3*t)-math.cos(4*t) |
| pts.append((c+x*2.4*AA,c-y*2.4*AA)) |
| d.polygon(pts,fill=255) |
| else: |
| count={'triangle':3,'star':10,'diamond':4,'hexagon':6}[shape] |
| pts=[] |
| for j in range(count): |
| theta=-math.pi/2+j*2*math.pi/count;r=(43 if shape!='star' or j%2==0 else 20)*AA |
| pts.append((c+r*math.cos(theta),c+r*math.sin(theta))) |
| d.polygon(pts,fill=255) |
| m=m.rotate(angle,resample=Image.Resampling.BICUBIC) |
| bbox=m.getbbox();m=m.crop(bbox);width,height=size |
| return m.resize((int(width*AA),int(height*AA)),Image.Resampling.LANCZOS) |
|
|
| def make_scene(seed,index): |
| rng=np.random.default_rng(seed*100000+index) |
| for attempt in range(100): |
| shape=SHAPES[(index+seed)%len(SHAPES)];color=str(rng.choice(list(COLORS)));other=str(rng.choice([c for c in COLORS if c!=color])) |
| ashape=str(rng.choice([s for s in SHAPES if s!=shape]));acolor=str(rng.choice([c for c in COLORS if c not in (color,other)])) |
| identities=[(color,shape)]*3+[(other,shape),(acolor,ashape)] |
| count=int(rng.integers(9,14)) |
| while len(identities)<count: |
| c=str(rng.choice(list(COLORS)));s=str(rng.choice(SHAPES)) |
| if (c,s) not in ((color,shape),(other,shape),(acolor,ashape)):identities.append((c,s)) |
| specs=[];masks=[];ok=True |
| for j,(c,s) in enumerate(identities): |
| width=int(rng.integers(46,77));height=int(width*rng.uniform(.85,1.18));angle=float(rng.uniform(-165,165)) |
| mask=object_mask(s,(width,height),angle) |
| for trial in range(150): |
| x=int(rng.integers(15,S-width-15));y=int(rng.integers(15,S-height-15)) |
| canvas=Image.new('L',(S*AA,S*AA));canvas.paste(mask,(x*AA,y*AA)) |
| b=np.asarray(canvas.resize((S,S),Image.Resampling.LANCZOS))>=128 |
| if all(np.logical_and(b,p).sum()<.22*min(b.sum(),p.sum()) for p in masks):break |
| else:ok=False;break |
| masks.append(b);specs.append(dict(id=j+1,color=c,shape=s,x=x,y=y,width=width,height=height,angle=angle,texture=str(rng.choice(['solid','stripes','dots','grid','checker','satin'])),texture_phase=int(rng.integers(0,12)))) |
| if not ok:continue |
| owner=np.zeros((S,S),np.uint8) |
| for j,b in enumerate(masks):owner[b]=j+1 |
| fractions=[(owner==j+1).sum()/b.sum() for j,b in enumerate(masks)] |
| if min(fractions)<.7:continue |
| centroids=[] |
| for j in range(count): |
| yy,xx=np.nonzero(owner==j+1);centroids.append((float(xx.mean()/S),float(yy.mean()/S))) |
| axes=[] |
| for ax in [0,1]: |
| ds=[centroids[j][ax]-centroids[4][ax] for j in range(3)] |
| if min(ds)<-.09 and max(ds)>.09 and min(abs(v) for v in ds)>.045:axes.append(ax) |
| if not axes:continue |
| axis=axes[index%len(axes)];first,second=('left','right') if axis==0 else ('above','below') |
| left=[j+1 for j in range(3) if centroids[j][axis]<centroids[4][axis]];right=[j+1 for j in range(3) if centroids[j][axis]>centroids[4][axis]] |
| target=f'{color} {plural(shape)}';atarget=f'{other} {plural(shape)}';anchor=f'{acolor} {ashape}' |
| relation=lambda rel:f'segment all {target} '+(f'{rel} of the {anchor}' if axis==0 else f'{rel} the {anchor}') |
| missing=next(c for c in COLORS if all((o['color'],o['shape'])!=(c,shape) for o in specs)) |
| extreme=min(range(3),key=lambda j:centroids[j][0])+1 |
| pair_specs=[('attribute',[f'segment all {target}',f'segment all {atarget}'],[[1,2,3],[4]]),('relational',[relation(first),relation(second)],[left,right]),('multi_target',[f'segment the leftmost {color} {shape}',f'segment all {target}'],[[extreme],[1,2,3]]),('negative_action',[f'segment all {target}',f'do not segment all {target}'],[[1,2,3],[]]),('empty_target',[f'segment all {target}',f'segment all {missing} {plural(shape)}'],[[1,2,3],[]]),('paraphrase',[f'segment all {target}',f'show every {color} {shape}'],[[1,2,3],[1,2,3]])] |
| meta=dict(seed=seed,index=index,objects=specs,visible_fraction=fractions,centroids=centroids,occupancy=float((owner>0).mean()),relation_axis=axis,pairs=pair_specs) |
| return meta,owner |
| raise RuntimeError((seed,index,'placement_failed')) |
|
|
| def render(meta,rich): |
| rng=np.random.default_rng(meta['seed']*100000+meta['index']+923471) |
| n=S*AA;yy,xx=np.mgrid[:n,:n];base=np.array([(251,249,244),(245,249,248),(249,245,250),(246,248,253)][meta['index']%4],float) |
| if rich: |
| noise=rng.normal(0,1.15,(n,n));shade=(xx/n-.5)*1.3+(yy/n-.5)*1.8 |
| arr=np.clip(base[None,None,:]+(noise+shade)[...,None],0,255).astype('uint8') |
| else:arr=np.broadcast_to(base.astype('uint8'),(n,n,3)).copy() |
| image=Image.fromarray(arr).convert('RGBA') |
| if rich and meta['index']%3==0: |
| d=ImageDraw.Draw(image) |
| for x in range(0,n,20*AA):d.line((x,0,x,n),fill=(192,202,202,20),width=1) |
| for y in range(0,n,20*AA):d.line((0,y,n,y),fill=(192,202,202,20),width=1) |
| for o in meta['objects']: |
| mask=object_mask(o['shape'],(o['width'],o['height']),o['angle']);w,h=mask.size |
| if rich: |
| shadow=Image.new('RGBA',(n,n));sm=Image.new('L',(n,n));sm.paste(mask,(o['x']*AA+3*AA,o['y']*AA+4*AA));sm=sm.filter(ImageFilter.GaussianBlur(2.2*AA)).point(lambda p:int(p*.24));shadow.putalpha(sm);image=Image.alpha_composite(image,shadow) |
| y,x=np.mgrid[:h,:w];rgb=np.array(COLORS[o['color']],float);factor=np.zeros((h,w)) |
| if rich: |
| phase=o['texture_phase']*AA;pattern=o['texture'] |
| if pattern=='stripes':factor=np.where((x+y+phase)%(12*AA)<3*AA,.28,-.015) |
| elif pattern=='dots':factor=np.where(((x+phase)%(15*AA)-7*AA)**2+((y+phase)%(15*AA)-7*AA)**2<(2.4*AA)**2,.42,0.) |
| elif pattern=='grid':factor=np.where(((x+phase)%(13*AA)<2*AA)|((y+phase)%(13*AA)<2*AA),-.20,.06) |
| elif pattern=='checker':factor=np.where(((x//(11*AA)+y//(11*AA))%2)==0,.20,-.13) |
| elif pattern=='satin':factor=.22*np.cos((x+y)/(11*AA)) |
| factor+=.08*(1-y/max(h,1))-.025+rng.normal(0,.012,(h,w)) |
| pixels=np.where(factor[...,None]>=0,rgb+(255-rgb)*factor[...,None],rgb*(1+factor[...,None])) |
| tile=Image.fromarray(np.clip(pixels,0,255).astype('uint8')).convert('RGBA') |
| |
| inner=mask.filter(ImageFilter.MinFilter(3));edge=(np.asarray(mask,dtype=float)-np.asarray(inner,dtype=float))/255 |
| a=np.asarray(tile).copy();a[...,:3]=(a[...,:3]*(1-.22*edge[...,None])).astype('uint8');tile=Image.fromarray(a);tile.putalpha(mask) |
| image.alpha_composite(tile,(o['x']*AA,o['y']*AA)) |
| return image.convert('RGB').resize((S,S),Image.Resampling.LANCZOS) |
|
|
| def main(): |
| ap=argparse.ArgumentParser();ap.add_argument('--per-seed',type=int,default=240);ap.add_argument('--seeds',type=int,nargs='+',default=[11,23,37,53,71]);a=ap.parse_args() |
| dest=ROOT/'data/rich';dest.mkdir(parents=True,exist_ok=True);rows=[];scenes=[] |
| for seed in a.seeds: |
| for index in range(a.per_seed): |
| meta,owner=make_scene(seed,index);sid=f'r{seed}_{index:04d}';meta['scene_id']=sid;scenes.append(meta) |
| sd=dest/sid;sd.mkdir(exist_ok=True);Image.fromarray(owner).save(sd/'instances.png') |
| for style in ['flat','rich']: |
| ip=sd/f'{style}.png';render(meta,style=='rich').save(ip) |
| for family,queries,targets in meta['pairs']: |
| for endpoint,(query,ids) in enumerate(zip(queries,targets)): |
| gp=sd/f'{family}_{endpoint}.png';gt=np.isin(owner,ids) |
| if not gp.exists():Image.fromarray(gt.astype('uint8')*255).save(gp) |
| rows.append(dict(id=f'{sid}_{style}_{family}_{endpoint}',scene_id=sid,domain='rich_synthetic',split='test',mode=family,pair_id=f'{sid}_{style}_{family}',endpoint=endpoint,target_count=len(ids),query=query,image_path=str(ip.relative_to(ROOT)),gt_path=str(gp.relative_to(ROOT)),seed=seed,corruption=style,template='scene_graph',render=style,object_count=len(meta['objects']),occupancy=meta['occupancy'],target_instance_ids=ids)) |
| if index%40==0:print('SCENE',sid,'records',len(rows),flush=True) |
| p=ROOT/'data/rich_synthetic.jsonl';p.write_text(''.join(json.dumps(r)+'\n' for r in rows));(ROOT/'data/rich_scenes.jsonl').write_text(''.join(json.dumps(r)+'\n' for r in scenes)) |
| meta=dict(scenes=len(scenes),images=2*len(scenes),records=len(rows),args=vars(a),manifest_sha256=hashlib.sha256(p.read_bytes()).hexdigest(),mean_objects=float(np.mean([len(s['objects']) for s in scenes])),min_visible_fraction=min(min(s['visible_fraction']) for s in scenes),mean_occupancy=float(np.mean([s['occupancy'] for s in scenes])),renderer='Pillow procedural raster; no image generation model; common instance masks across render styles') |
| (ROOT/'protocol/rich_manifest.json').write_text(json.dumps(meta,indent=2));print(json.dumps(meta,indent=2),flush=True) |
| if __name__=='__main__':main() |
|
|