def asgray(im):
    """
    Takes an image and returns its grayscale version by averaging the color
    channels.  if an alpha channel is present, it will simply be ignored. If a
    grayscale image is given, the original image is returned.

    Parameters
    ----------
    image : ndarray, ndim 2 or 3
        RGB or grayscale image.

    Returns
    -------
    gray_image : ndarray, ndim 2
        Grayscale version of image.
    """
    if im.ndim == 2:
        return im
    elif im.ndim == 3 and im.shape[2] in (3, 4):
        return im[..., :3].mean(axis=-1)
    else:
        raise ValueError('Invalid image format')