matplotlib中等于skimage.io.imread(fname, as_grey=True)的功能是什么?

2 投票
3 回答
3896 浏览
提问于 2025-04-18 02:08

因为这是一个非常常见的做法……我在想,matplotlib有没有和这个scikit-image里的函数相对应的功能呢?

from skimage import io
im = io.imread(fname, as_grey=True)

有没有办法直接把RGB文件转换成灰度图?

我需要用matplotlib的功能,因为我想用它来绘制结果。而且我发现,通过io.imread读取的数组和通过plt.imread读取的数组似乎不一样。

谢谢!

3 个回答

0

你也可以使用 scipy.misc.imread 这个函数,并设置 flatten=True。这个方法需要你先安装PIL库,但它会返回一个数组对象。

Docstring:
Read an image file from a filename.

Parameters
----------
name : str
    The file name to be read.
flatten : bool, optional
    If True, flattens the color layers into a single gray-scale layer.

Returns
-------
imread : ndarray
    The array obtained by reading image from file `name`.

Notes
-----
The image is flattened by calling convert('F') on
the resulting image object.
1

如果你安装了PIL这个库,那么你可以把文件读取成一个灰度的PIL图像,然后再把它转换成一个NumPy数组:

import Image

img = Image.open(FILENAME).convert('L')
arr = np.array(img)
5

你可以使用 matplotlib.pyplot.imread 来读取图像。这样你会得到一个 RGB 或 RGBA 格式的图像。如果你得到的是 RGBA 图像,你可能想要去掉透明度这一层:

rgb = rgba[..., :3]

你可以通过以下方式得到一个灰度图像的近似值:

rgb.mean(axis=2)

不过,这样做并不完全正确。正确的方法是给不同的颜色通道乘上不同的权重,然后再把它们组合在一起,也就是说:

([0.2125, 0.7154, 0.0721] * rgb).sum(axis=2)

撰写回答