問題:
我正嘗試使用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()
|