Splitting Images with cv.split()
Splitting an image is the process of decomposing an image by its channels to simplify image processing operations. Image splitting is done when there is a need to manipulate images at the channel level in order to preserve image as a whole ((i.e. performing operation on all 3 channels may lead to unexpected results).
Splitting implementation in numpy
Splitting an image in numpy is achieved through index slicing. In practice, it looks like this:
import cv2
import numpy as np
import matplotlib.pyplot as plt
# reading the image
bear = cv2.imread('bear.jpg', cv2.IMREAD_COLOR)
bear = cv2.cvtColor(bear, cv2.COLOR_BGR2RGB)
# display image
plt.imshow(bear)
plt.axis('off')
Splitting image with numpy index slicing
red, green, blue = bear[:, :, 0], bear[:, :, 1], bear[:, :, 2]
red.shape, green.shape, blue.shape
((427, 640), (427, 640), (427, 640))
Notice that all channels have the same dimension
Visualizing Channel level images
Each channel is an image emphasizes pixel intensity for it's respective color. Below is the visualization of all channels normalized by gray in order to observe pixel intensity differences.
fig = plt.figure(figsize=(15, 10))
fig.add_subplot(221)
plt.imshow(blue, cmap='gray')
plt.title('blue channel, cmap=gray')
plt.axis('off')
fig.add_subplot(222)
plt.imshow(green, cmap='gray')
plt.title('green channel, cmap=gray')
plt.axis('off')
fig.add_subplot(223)
plt.imshow(red, cmap='gray')
plt.title('red channel, cmap=gray')
plt.axis('off')
fig.add_subplot(224)
plt.imshow(bear)
plt.title('all colors')
plt.axis('off')
plt.tight_layout()
plt.savefig('bear_splitting_channels_with_numpy.png')
Notice that, view in gray scale, pixel intensities across channels vary. For example, the red channel has mostly light (high) intensity pixels because the original image has little red elements. However, on the bear, the blue and green channels have lower pixel intensity which combine to the final yellow.
Splitting Images with OpenCV
OpenCV offers a function to decompose an image into its channels like in the numpy example above. cv2.split() function splits an image into channels
r, g, b = cv2.split(bear)
b.shape, g.shape, r.shape
((427, 640), (427, 640), (427, 640))