import torch


def flow_warp(img: torch.Tensor, flow: torch.Tensor) -> torch.Tensor:
    """Warp an image or feature map with optical flow

    From:
    https://www.programcreek.com/python/example/104458/torch.nn.functional.grid_sample

    Args:
        x (Tensor): size (N, C, H, W)
        flow (Tensor): size (N, H, W, 2), normal value
        interp_mode (str): 'nearest' or 'bilinear'
        padding_mode (str): 'zeros' or 'border' or 'reflection'

    Returns:
        Tensor: warped image or feature map
    """
    B, C, H, W = img.size()
    # mesh grid
    grid_y, grid_x = torch.meshgrid(torch.arange(0, H), torch.arange(0, W))
    grid = torch.stack((grid_x, grid_y), 2).float()  # W(x), H(y), 2
    grid.requires_grad = False
    grid = grid.type_as(img)
    vgrid = grid[None] + flow.permute(0, 2, 3, 1)
    # scale grid to [-1,1]
    vgrid_x = 2.0 * vgrid[:, :, :, 0] / max(W - 1, 1) - 1.0
    vgrid_y = 2.0 * vgrid[:, :, :, 1] / max(H - 1, 1) - 1.0
    vgrid_scaled = torch.stack((vgrid_x, vgrid_y), dim=3)
    output = torch.nn.functional.grid_sample(
        img, vgrid_scaled, mode="bilinear", padding_mode="border"
    )
    return output