如何在Python中将RGB图像转换为灰度图像? [英] How can I convert an RGB image into grayscale in Python?

查看:998
本文介绍了如何在Python中将RGB图像转换为灰度图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用matplotlib读取RGB图像并将其转换为灰度.

I'm trying to use matplotlib to read in an RGB image and convert it to grayscale.

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

In matlab I use this:

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

matplotlib教程中,他们没有对此进行介绍.他们只是读图片

In the matplotlib tutorial they don't cover it. They just read in the image

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

然后将它们切成薄片,但这与从我所了解的将RGB转换为灰度不同.

and then they slice the array, but that's not the same thing as converting RGB to grayscale from what I understand.

lum_img = img[:,:,0]

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

I find it hard to believe that numpy or matplotlib doesn't have a built-in function to convert from rgb to gray. Isn't this a common operation in image processing?

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

I wrote a very simple function that works with the image imported using imread in 5 minutes. It's horribly inefficient, but that's why I was hoping for a professional implementation built-in.

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

Sebastian has improved my function, but I'm still hoping to find the built-in one.

matlab(NTSC/PAL)的实现:

matlab's (NTSC/PAL) implementation:

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

推荐答案

如何使用枕头:

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()

这篇关于如何在Python中将RGB图像转换为灰度图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆