def img_to_gray(img):
    """
    Tranform a RGB image into a grayscale image
    :param img: RGB image
    :return: grayscale image
    """
    if len(img.shape) < 3 or img.shape[2] == 1:
        return img.reshape(img.shape + (1,))
    else:
        r, g, b = img[:, :, 0], img[:, :, 1], img[:, :, 2]
        return (0.2989 * r + 0.5870 * g + 0.1140 * b).reshape((img.shape[0], img.shape[1], 1)).astype(img.dtype)