In this chapter, you will learn how to split an image into its constituent bands and how to merge bands into a single image using Pillow.
getbands()
The getbands()
method returns a tuple containing the bands which are present in the image. For example, an RGB image contains 3 bands- ‘R’ (Red), ‘G’ (Green), and ‘B’ (Blue).
Example
# stores the bands of img as a tuple in bands
bands = img.getbands()
print(bands)
# Outputs- ('R', 'G', 'B')
split()
The split() method is used to split an image into its constituent bands. split()
returns a tuple in which each element is an image containing one band from the original image.
Example
In this example, r
, g
, and b
are objects of Image
class and contain one band each(Red, Green, and Blue respectively) from the original image.
# Split the image into its constituent bands
r, g, b = img.split()
print(type(r))
# Outputs- <class 'PIL.Image.Image'>
print(img.size)
# Outputs- (3264, 2448)
print(r.size)
# Outputs- (3264, 2448)
print(r.mode)
# Outputs- 'L'
Note– Since each of the images r
, g
, and b
have just one band, they have their mode defined by ‘L’.
merge()
The merge()
function is used to merge various bands of an image into a single image. The mode of the image to be created from the bands is passed to the merge()
function along with a sequence that consists of the bands you want to merge.
Example
In this example, we will be merging the bands we split from the original image. Since we will be merging the bands in the same order in which they were split, we will get back the original image.
# Merging the bands in which they were split and storing it in merged_img
merged_img = Image.merge('RGB', (r, g, b))
merged_img.show()
The output of this will be-
Example
In this example, we will be merging the bands in the opposite order in which they were split. Hence, the red and the blue bands will be interchanged.
# Merging the bands in the opposite order in which they were split and storing it in merged_img
merged_img_2 = Image.merge('RGB', (b, g, r))
merged_img_2.show()
The output of this will be-
Example
In this example, we will be merging the bands in an even different way. We will replace red with green, green with blue, and blue with red.
merged_img_3 = Image.merge('RGB', (g, b, r))
merged_img_3.show()
The output of this will be-
Example
We can also merge different bands using a different mode. In this example, we will merge the bands R, G, and B using ‘HSV’ mode. The respective values of Red, Green, and Blue will be assigned to Hue, Saturation, and Value.
merged_img_4 = Image.merge('HSV', (r, g, b))
merged_img_4.show()
The output of this will be-