
正文
python实现RGB转化为灰度图像
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
问题:
我正尝试使用matplotlib读取RGB图像并将其转换为灰度。
在matlab中,我使用这个:
1 | img = rgb2gray(imread('image.png')); |
在matplotlib tutorial中他们没有覆盖它。他们只是在图像中阅读
1 2 | import matplotlib.image as mpimgimg = mpimg.imread('image.png') |
然后他们切片数组,但是这不是从我所了解的将RGB转换为灰度。
1 | lum_img = img[:,:,0] |
编辑:
我发现很难相信numpy或matplotlib没有内置函数来从rgb转换为灰色。这不是图像处理中的常见操作吗?
我写了一个非常简单的函数,它可以在5分钟内使用imread导入的图像。这是非常低效的,但这就是为什么我希望内置专业实施。
塞巴斯蒂安改善了我的功能,但我仍然希望找到内置的一个。
matlab的(NTSC / PAL)实现:
1 2 3 4 5 6 7 8 | import numpy as npdef rgb2gray(rgb): r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2] gray = 0.2989 * r + 0.5870 * g + 0.1140 * b return gray |
回答:
如何使用PIL
1 2 3 | from PIL import Imageimg = Image.open('image.png').convert('LA')img.save('greyscale.png') |
使用matplotlib和the formula
1 | Y' = 0.299 R + 0.587 G + 0.114 B |
你可以这样做:
1 2 3 4 5 6 7 8 9 10 11 | import numpy as npimport matplotlib.pyplot as pltimport matplotlib.image as mpimgdef rgb2gray(rgb): return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])img = mpimg.imread('image.png') gray = rgb2gray(img) plt.imshow(gray, cmap = plt.get_cmap('gray'))plt.show() |





