Python如何将RGB图像转换为Pytho灰度图像?


我正尝试使用matplotlib读取RGB图像并将其转换为灰度。
在matlab中,我使用这个:

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

matplotlib tutorial中他们没有覆盖它。他们只是在图像中阅读

1
2
import  matplotlib.image as mpimg
img =  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 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

回答:

如何使用PIL

1
2
3
from  PIL import  Image
img =  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 np
import  matplotlib.pyplot as plt
import  matplotlib.image as mpimg
 
def  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()


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM