Skip to main content
 首页 » 编程设计

python之如何使用 pyplot 正确显示图像的红色、绿色和蓝色 (rgb) channel

2025年02月15日7xing901022

我有一个小项目,所以一周前我开始在 Python 上做一些测试。我必须显示 rgb 图像的 3 个 channel ,但 pyplot.imshow() 函数显示以下内容:

我想显示红色、绿色和蓝色 channel ,如下所示:

到目前为止,这是我的代码:

from matplotlib import pyplot as plt 
from PIL import Image 
import numpy as np 
 
img1 = np.array(Image.open('img1.png')) 
figure, plots = plt.subplots(ncols=3, nrows=1) 
for i, subplot in zip(range(3), plots): 
    temp = np.zeros(img1.shape, dtype='uint8') 
    temp = img1[:,:,i] 
    subplot.imshow(temp) 
    subplot.set_axis_off() 
plt.show() 

我不在任何笔记本上工作。相反,我在 PyCharm 工作。我读了这篇文章:24739769 .我检查了一下,img1.dtype 是 uint8,所以我不知道如何显示我想要的内容。

请您参考如下方法:

您只需要一个微小的更改:temp[:,:,i] = img1[:,:,i]。

使用您展示的第一张图片的完整且可验证的示例:

from matplotlib import pyplot as plt 
from PIL import Image 
import numpy as np 
 
img1 = np.array(Image.open('img1.png')) 
figure, plots = plt.subplots(ncols=3, nrows=1) 
for i, subplot in zip(range(3), plots): 
    temp = np.zeros(img1.shape, dtype='uint8') 
    temp[:,:,i] = img1[:,:,i] 
    subplot.imshow(temp) 
    subplot.set_axis_off() 
plt.show()