使用Python Imaging Library隔离单个通道



假设我有一个图像,我想让它只显示红色通道,并且图像看起来是红色的,我该如何使用PIL来做到这一点?谢谢

您可以使用PIL的Image.split()操作将图像分离为多个波段:

img = Image.open("image.jpg")
red, green, blue = img.split()

如果图像具有alpha通道(RGBA),则分割函数将默认返回该通道。点击此处了解更多信息。

我找到了答案。与其使用im.split()将带转换为灰度,我应该将Image转换为一个数组,将我不想要的带乘以0,然后将其转回Image对象。

导入图像和numpy,我做了以下操作:

a = Image.open("image.jpg")
a = numpy.array(a)
a[:,:,0] *=0
a[:,:,1] *=0
a = Image.fromarray(a)
a.show()

这将显示一个蓝色图像。

这里很晚了,但因为我们处理的是numpy,所以我们可以使用布尔索引。

def channel(img, n):
    """Isolate the nth channel from the image.
       n = 0: red, 1: green, 2: blue
    """
    a = np.array(img)
    a[:,:,(n!=0, n!=1, n!=2)] *= 0
    return Image.fromarray(a)

对于希望从图像中提取单个通道的人(而不是生成具有R、G和B通道的图像,但G和B信道均为零),您可以执行以下操作:

img = Image.open("image.jpg")
red = img.getchannel('R')
# OR
red = img.getchannel(0)  # Avoids internal lookup of 'R' in img.getbands()

最新更新