Python 使用PIL更换通道

Python 使用PIL更换通道,python,python-imaging-library,Python,Python Imaging Library,我目前正在开发一个工具,其中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. 最好的方法是

我目前正在开发一个工具,其中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.
最好的方法是什么?

您有和其他方法

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')
winter.jpg

spring.jpg

output.jpg


最好的方法是阅读文档,如果要更换
X
的所有频道,首先为什么需要
X
?输出中不会留下任何内容。到底是什么问题?你试过什么,做过什么研究吗?堆栈溢出不是免费的代码编写服务。请看:,@AMC我做了一些研究,但什么也没发现。这就是问题所在。我不是在这里寻找免费代码。欢迎新stackoverflow成员的方式:)谢谢您的帮助。这是我追求的边缘。我想合并集成第二,第三和第四图像作为RGB通道的第一个。它确实给了我正确的方法。我最终将RGB更改为灰度模式,否则它不允许我将图像复制到RGB通道。所以非常感谢:)