我试图使用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分钟内导入图像。它的效率非常低,但这就是为什么我希望内置一个专业的实现。

塞巴斯蒂安改进了我的功能,但我仍然希望找到内置的功能。

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

当前回答

如果你已经在使用NumPy/SciPy,你可以使用:

scipy.ndimage。imread (file_name模式= ' L ')

其他回答

你也可以使用scikit-image,它提供了一些函数来转换ndarray中的图像,比如rgb2gray。

from skimage import color
from skimage import io

img = color.rgb2gray(io.imread('image.png'))

注:此转换中使用的权重是针对当代CRT荧光粉校准的:Y = 0.2125 R + 0.7154 G + 0.0721 B

或者,您可以通过以下方法读取灰度图像:

from skimage import io
img = io.imread('image.png', as_gray=True)

你可以使用OpenCV的imread从一开始就读取灰度图像文件:

img = cv2.imread('messi5.jpg', 0)

此外,如果你想读取图像为RGB,做一些处理,然后转换为灰度,你可以使用cvtcolor从OpenCV:

gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

The tutorial is cheating because it is starting with a greyscale image encoded in RGB, so they are just slicing a single color channel and treating it as greyscale. The basic steps you need to do are to transform from the RGB colorspace to a colorspace that encodes with something approximating the luma/chroma model, such as YUV/YIQ or HSL/HSV, then slice off the luma-like channel and use that as your greyscale image. matplotlib does not appear to provide a mechanism to convert to YUV/YIQ, but it does let you convert to HSV.

尝试使用matplotlib.colors.rgb_to_hsv(img),然后从数组中切片最后一个值(V)来获取灰度。它与亮度值不完全相同,但它意味着您可以在matplotlib中完成所有操作。

背景:

http://matplotlib.sourceforge.net/api/colors_api.html http://en.wikipedia.org/wiki/HSL_and_HSV

或者,您可以使用PIL或内置的colorsys.rgb_to_yiq()来转换为具有真正亮度值的色彩空间。你也可以完全投入到你自己的光转换器中,尽管这可能有点过头了。

我通过谷歌找到了这个问题,寻找一种将已经加载的图像转换为灰度的方法。

下面是一种使用SciPy的方法:

import scipy.misc
import scipy.ndimage

# Load an example image
# Use scipy.ndimage.imread(file_name, mode='L') if you have your own
img = scipy.misc.face()

# Convert the image
R = img[:, :, 0]
G = img[:, :, 1]
B = img[:, :, 2]
img_gray = R * 299. / 1000 + G * 587. / 1000 + B * 114. / 1000

# Show the image
scipy.misc.imshow(img_gray)

最快和当前的方式是使用枕头,安装通过pip安装枕头。

代码是:

from PIL import Image
img = Image.open('input_file.jpg').convert('L')
img.save('output_file.jpg')