import torch


def norm_quantize(tensor, per_channel=False):
    """Normalize between [0, 1] and quantize to 255 image levels."""
    if per_channel:
        t_min = tensor.min(-1, keepdim=True)[0].min(-2, keepdim=True)[0].min(0, keepdim=True)[0]
        t_max = tensor.max(-1, keepdim=True)[0].max(-2, keepdim=True)[0].max(0, keepdim=True)[0]
        norm = (tensor - t_min) / (t_max - t_min)
    else:
        norm = (tensor - tensor.min()) / (tensor.max() - tensor.min())

    quant = torch.round(norm*255)/255
    return quant