"""Read selected public images and their two resized polygon masks."""
import json
from pathlib import Path

import cv2
import numpy as np
from PIL import Image

def load_pair(index,row):
    path=Path('/tmp/diatom-neighbors')/f'{index:02d}.jpg'
    image=np.asarray(Image.open(path).convert('RGB'));h,w=image.shape[:2]
    assert (w,h)==(row['image']['width'],row['image']['height'])
    scale=768/max(w,h);W,H=round(w*scale),round(h*scale)
    image=cv2.resize(image,(W,H),interpolation=cv2.INTER_AREA)
    data=json.loads((Path('/tmp/diatom-mask-coco')/row['annotation_file']).read_text())
    annotations=[next(a for a in data['annotations'] if a['id']==k and a['image_id']==row['image']['id']) for k in row['annotation_ids']]
    masks=[]
    for ann in annotations:
        mask=np.zeros((H,W),dtype=np.uint8)
        for polygon in ann['segmentation']:
            xy=np.asarray(polygon,dtype=np.float32).reshape(-1,2);xy[:,0]*=W/w;xy[:,1]*=H/h
            cv2.fillPoly(mask,[np.rint(xy).astype(np.int32)],1)
        if not mask.any():raise ValueError('Empty polygon')
        masks.append(mask)
    return image,masks,path
