如何在Python中将RGB图像转换为灰度图像?

发布于 2021-02-02 23:19:45

我试图用来matplotlib读取RGB图像并将其转换为灰度。

在matlab中,我使用以下代码:

img = rgb2gray(imread('image.png'));

在matplotlib教程中,他们没有介绍。他们只是读了图像

import matplotlib.image as mpimg
img = mpimg.imread('image.png')

然后将它们切成薄片,但这与根据我的理解将RGB转换为灰度不是同一回事。

lum_img = img[:,:,0]

我发现很难相信numpy或matplotlib没有将rgb转换为灰色的内置函数。这不是图像处理中的常见操作吗?

我写了一个非常简单的函数,可以imread在5分钟内使用导入的图像。这是非常低效的,但这就是为什么我希望内置一个专业的实现。

Sebastian改进了我的功能,但我仍然希望找到内置的功能。

matlab(NTSC / PAL)的实现:

import numpy as np

def rgb2gray(rgb):

    r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b

    return gray
关注者
0
被浏览
165
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    Pillow怎么做:

    from PIL import Image
    img = Image.open('image.png').convert('LA')
    img.save('greyscale.png')
    使用matplotlib和公式
    
    Y' = 0.2989 R + 0.5870 G + 0.1140 B 
    

    你可以做:

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg
    
    def rgb2gray(rgb):
        return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])
    
    img = mpimg.imread('image.png')     
    gray = rgb2gray(img)    
    plt.imshow(gray, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
    plt.show()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看