我正在尝试使用matplotlib
读取RGB图像并将其转换为灰度。
在matlab中,我使用的是:
img = rgb2gray(imread('image.png'));
在matplotlib tutorial中,他们不会覆盖它。他们只是在图像中读出
import matplotlib.image as mpimg
img = mpimg.imread('image.png')
然后他们对数组进行切片,但根据我的理解,这与将RGB转换为灰度不是一回事。
lum_img = img[:,:,0]
我发现很难相信numpy或matplotlib没有内置的函数来从rgb转换为灰色。这不是图像处理中的常见操作吗?
我写了一个非常简单的函数,可以在5分钟内处理使用imread
导入的图像。它的效率非常低,但这就是为什么我希望有一个专业的内置实现。
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
发布于 2012-08-31 00:48:29
用Pillow怎么样?
from PIL import Image
img = Image.open('image.png').convert('L')
img.save('greyscale.png')
如果输入图像中存在alpha (透明度)通道并应保留该通道,请使用模式LA
img = Image.open('image.png').convert('LA')
使用matplotlib和the formula
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()
发布于 2015-01-16 18:56:03
发布于 2015-12-02 23:25:33
最快也是最流行的方式是使用通过pip install Pillow
安装的Pillow。
然后代码是:
from PIL import Image
img = Image.open('input_file.jpg').convert('L')
img.save('output_file.jpg')
https://stackoverflow.com/questions/12201577
复制相似问题