Bartłomiej 'furas' Burek
furas.pl
# prywatne notatki - Python, Linux, Machine Learning, etc.

Pillow: How to split and merge channels in RGB image using Python

You have split() and merge() to work with channels.

You can also use getchannel()

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()

You can also convert to numpy array and work with array.

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()

Minimal example with output.

from PIL import Image
import numpy as np

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:

python pillow split and merge channels RGB

spring.jpg

python pillow split and merge channels RGB

output.jpg

python pillow split and merge channels RGB
Książki: python-dla-kazdego-podstawy-programowania python-wprowadzenie python-leksykon-kieszonkowy python-receptury python-programuj-szybko-i-wydajnie python-projekty-do-wykorzystania black-hat-python-jezyk-python-dla-hackerow-i-pentesterow efektywny-python-59-sposobow-na-lepszy-kod tdd-w-praktyce-niezawodny-kod-w-jezyku-python aplikacje-internetowe-z-django-najlepsze-receptury