Замена канала с использованием PIL - PullRequest
0 голосов
/ 17 февраля 2020

В настоящее время я работаю над инструментом, в котором необходимо заменить каналы 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 Ответ

0 голосов
/ 17 февраля 2020

У вас есть 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')

winter.jpg

enter image description here

spring.jpg

enter image description here

output.jpg

enter image description here

...