import torch


def preprocess(tensor, to_y=True, crop_border=0):
    """Convert tensor of BGR to grayscale, and crop border.

    :param tensor: tensor
    :type tensor: torch.Tensor
    :param to_y: whether convert image from format bgr to format y
    :type to_y: bool
    :param crop_border: number of pixels to crop
    :type crop_border: int
    :return: grayscale tensor (if to_y is true), with border cropped, within range 0~1
    :rtype: torch.Tensor, in range 0~1
    """
    # crop boarders
    if crop_border > 0:
        tensor = tensor[:, :, crop_border:-crop_border, crop_border:-crop_border]
    # convert to y
    tensor /= 255.0
    if to_y:
        multiplier = torch.tensor([25.064, 129.057, 65.738]).view([3, 1, 1]).to(tensor.device) / 256.0
        tensor = torch.sum(tensor * multiplier, dim=1)
    return tensor