首页 > 解决方案 > 使用 PIL 进行通道替换

问题描述

我目前正在开发一种工具,其中需要将 1 个图像的通道替换为 3 个其他图像。

例如:

I have an image "X" and the channels would be X.r, X.g and X.b respectively.
I have 3 other images ["A","B","C"]
Those 3 images needs to replace the channels in X.

So the result would be X.A, X.B and X.C.

最好的方法是什么?

标签: pythonpython-imaging-library

解决方案


你有split()merge()等方法

from PIL import Image

img = Image.open('images/image.jpg')

r,g,b = img.split()

#r = img.getchannel(0)
#g = img.getchannel(1)
#b = img.getchannel(2)

img = Image.merge('RGB', (r,g,b))

img.show()

您还可以转换为 numpy 数组并使用数组

from PIL import Image
import numpy as np

img = Image.open('images/image.jpg')

arr = np.array(img)

r = arr[:,:,0]
g = arr[:,:,1]
b = arr[:,:,2]

arr[:,:,0] = r
arr[:,:,1] = g
arr[:,:,2] = b

img = Image.fromarray(arr)

img.show()

例子

from PIL import Image

img1 = Image.open('winter.jpg')
img2 = Image.open('spring.jpg')

r1,g1,b1 = img1.split()
r2,g2,b2 = img2.split()

new_img = Image.merge('RGB', (r1,g2,b2))

new_img.show()

new_img.save('output.jpg')

冬天.jpg

在此处输入图像描述

春天.jpg

在此处输入图像描述

输出.jpg

在此处输入图像描述


推荐阅读