如何对 Python 中的图像进行去饱和处理?

How to desaturate the image in Python?

我正在研究将灰色图像转换为彩色图像的代码,但在此之前,代码借助给定代码行将输入图像转换为去饱和图像:

def load_image(path):
    img = imread(path)
    # crop image from center
    short_edge = min(img.shape[:2])
    yy = int((img.shape[0] - short_edge) / 2)
    xx = int((img.shape[1] - short_edge) / 2)
    crop_img = img[yy : yy + short_edge, xx : xx + short_edge]
    # resize to 224, 224
    img = skimage.transform.resize(crop_img, (224, 224))
    # desaturate image
    return (img[:,:,0] + img[:,:,1] + img[:,:,2]) / 3.0

我在这一行中遇到错误,错误读作:

return (img[:,:,0] + img[:,:,1] + img[:,:,2]) / 3.0
IndexError: too many indices for array

请帮助我解决我面临的问题。

您的大部分代码都适用于 2D(灰度)或 3D (RGB) 数组。但是,最后一行明确需要一个 3D 数组。您可以添加一个条件来传递二维数组,因为代码只是将通道平均在一起:

if img.ndim < 3:
    return img
# return average

或者,您可以在函数开始时一意识到您有一个二维数组就提出一个信息更丰富的错误。做有意义的事。

这不是降低图像饱和度的正确方法。请使用 skimage.color.rgb2gray,它可以毫无问题地应用于 2D 图像(已经去饱和)。

即将最后一行改为:

return color.rgb2gray(img)

并在脚本的前面添加 from skimage import color