RGB Color Model in Python
RGB (Red, Green, Blue) color model is widely used in digital image processing, computer graphics and web designing. It represents colors by combining red, green and blue at different intensities to produce a broad spectrum of colors. In this article, we'll take a deeper look at RGB colour model.
Implementation of RGB color model in Python
1. Loading and Displaying the Image
We'll start by setting up the necessary libraries like OpenCV, Numpy and Matplotlib. We will load the example image which can be downloaded from here.
import cv2
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread('Image.png')
By default, any image in opencv is loaded in the Blue-Green-Red (BGR) model.
plt.imshow(image)
plt.title('Image in BGR Mode')
plt.axis('off')
plt.show()
Output:

We'll then be converting the same image in RGB mode and displaying it.
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(image)
plt.title('Image in RGB Mode')
plt.axis('off')
plt.show()
Output:

2. Shape of the Image
The "shape" attribute returns the height, width and number of channels of an image. Since the RGB Model deals with colour images that have 3 channels.
height, width, num_channels = image.shape
print("Height:", height)
print("Width:", width)
print("No. of channels:", num_channels)
print("Total no. of pixels in the image:", height * width)
Output:

3. Printing first 10 pixels
Any colour image is basically a 3D matrix. In the RGB colour space the first channel represents the Red component, second and third channels represent the Green and Blue components respectively. Thus a pixel which is the smallest unit of an image is made up of three values: R, G and B.
In order to visualize values of pixel we'll be printing the first 10 pixels of this image. For this we need to flatten the 3D matrix into a 1D matrix with 3 columns each where each column represents a channel.
flat_image = image.reshape(-1, 3)
print("First 10 pixels (flattened):")
for i in range(10):
print(f"Pixel {i+1} (R value, G value, B value): {flat_image[i]}")
Output:

4. Extracting RGB Channels
The cv2 module also has a method to separate the channels. We will use cv2.split() function.
# Extract the RGB channels
r, g, b = cv2.split(image)
plt.figure(figsize=(10, 3))
plt.subplot(1, 3, 1)
plt.imshow(r, cmap='Reds')
plt.title('Red Channel')
plt.axis('off')
plt.subplot(1, 3, 2)
plt.imshow(g, cmap='Greens')
plt.title('Green Channel')
plt.axis('off')
plt.subplot(1, 3, 3)
plt.imshow(b, cmap='Blues')
plt.title('Blue Channel')
plt.axis('off')
plt.show()
Output:

5. Histogram Analysis of RGB Channels
In order to understand the colour distribution of each of the channels of this particular image, we'll look into its histogram.
plt.figure(figsize=(15, 5))
colors = ['red', 'green', 'blue']
channels = [R, G, B]
for i, (channel, color) in enumerate(zip(channels, colors)):
plt.subplot(1, 3, i+1)
plt.hist(channel.ravel(), bins=256, color=color, alpha=0.8)
plt.title(f'{color.capitalize()} Channel Histogram')
plt.xlabel('Intensity Value')
plt.ylabel('Frequency')
plt.show()
Output:

6. Statistical Analysis For Each Channel
We'll look into the mean, median, standard deviation, minimum and maximum values of each channels.
def channel_statistics(channel):
mean = np.mean(channel)
median = np.median(channel)
std_dev = np.std(channel)
min_val = np.min(channel)
max_val = np.max(channel)
return mean, median, std_dev, min_val, max_val
# Calculate statistics for each channel
stats = {}
for channel, color in zip(channels, colors):
stats[color] = channel_statistics(channel)
print('RGB Channel Statistics:')
for color, stat in stats.items():
print(
f'{color.capitalize()} Channel - Mean: {stat[0]:.2f}, Median: {stat[1]:.2f}, Std Dev: {stat[2]:.2f}, Min: {stat[3]}, Max: {stat[4]}')
Output:

7. Channel Correlation Analysis
We can obtain the correlation between each of the channels using correlation matrix.
R_flatten = R.ravel()
G_flatten = G.ravel()
B_flatten = B.ravel()
correlation_matrix = np.corrcoef([R_flatten, G_flatten, B_flatten])
print('Correlation Matrix:')
print(' R G B')
print(correlation_matrix)
plt.imshow(correlation_matrix, cmap='coolwarm', interpolation='none')
plt.colorbar()
plt.xticks([0, 1, 2], ['R', 'G', 'B'])
plt.yticks([0, 1, 2], ['R', 'G', 'B'])
plt.title('Correlation Matrix')
plt.show()
Output:

The color intensity of each cell in the heatmap visually represents correlation values with shades of red indicating higher correlations and blue shades indicating lower correlations. This matrix helps in understanding how the color channels relate to one another in a imagr which is useful in various image processing tasks.