def get_single_mapping_ind(bwd_flow, bwd_occ, imgs, scale=1.0):
    """
    FLATTEN: Optical fLow-guided attention (Temoporal-guided attention)
    Find the correspondence between every pixels in a pair of frames

    [input]
    bwd_flow: 1*2*H*W
    bwd_occ: 1*H*W      i.e., f2 = warp(f1, bwd_flow) * bwd_occ
    imgs: 2*3*H*W       i.e., [f1,f2]

    [output]
    mapping_ind: pixel index correspondence
    unlinkedmask: indicate whether a pixel has no correspondence
    i.e., f2 = f1[mapping_ind] * unlinkedmask
    """
    flows = F.interpolate(bwd_flow, scale_factor=1.0 / scale, mode="bilinear")[0][[1, 0]] / scale  # 2*H*W
    _, H, W = flows.shape
    masks = torch.logical_not(F.interpolate(bwd_occ[None], scale_factor=1.0 / scale, mode="bilinear") > 0.5)[
        0
    ]  # 1*H*W
    frames = F.interpolate(imgs, scale_factor=1.0 / scale, mode="bilinear").view(2, 3, -1)  # 2*3*HW
    grid = torch.stack(torch.meshgrid([torch.arange(H), torch.arange(W)]), dim=0).to(flows.device)  # 2*H*W
    warp_grid = torch.round(grid + flows)
    mask = torch.logical_and(
        torch.logical_and(
            torch.logical_and(torch.logical_and(warp_grid[0] >= 0, warp_grid[0] < H), warp_grid[1] >= 0),
            warp_grid[1] < W,
        ),
        masks[0],
    ).view(-1)  # HW
    warp_grid = warp_grid.view(2, -1)  # 2*HW
    warp_ind = (warp_grid[0] * W + warp_grid[1]).to(torch.long)  # HW
    mapping_ind = torch.zeros_like(warp_ind) - 1  # HW

    for f0ind, f1ind in enumerate(warp_ind):
        if mask[f0ind]:
            if mapping_ind[f1ind] == -1:
                mapping_ind[f1ind] = f0ind
            else:
                targetv = frames[0, :, f1ind]
                pref0ind = mapping_ind[f1ind]
                prev = frames[1, :, pref0ind]
                v = frames[1, :, f0ind]
                if ((prev - targetv) ** 2).mean() > ((v - targetv) ** 2).mean():
                    mask[pref0ind] = False
                    mapping_ind[f1ind] = f0ind
                else:
                    mask[f0ind] = False

    unusedind = torch.arange(len(mask)).to(mask.device)[~mask]
    unlinkedmask = mapping_ind == -1
    mapping_ind[unlinkedmask] = unusedind
    return mapping_ind, unlinkedmask

    FLATTEN: Optical fLow-guided attention (Temoporal-guided attention)
    Find the correspondence between every pixels in a pair of frames

    [input]
    bwd_flow: 1*2*H*W
    bwd_occ: 1*H*W      i.e., f2 = warp(f1, bwd_flow) * bwd_occ
    imgs: 2*3*H*W       i.e., [f1,f2]

    [output]
    mapping_ind: pixel index correspondence
    unlinkedmask: indicate whether a pixel has no correspondence
    i.e., f2 = f1[mapping_ind] * unlinkedmask
    
examples/community/fresco_v2v.py