0
0
Matplotlibdata~10 mins

Color channel handling in Matplotlib - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Color channel handling
Load Image as Array
Separate Color Channels
Red
Modify or Analyze Channels
Combine Channels Back
Display or Save Image
The image is loaded as an array, color channels are separated, optionally modified or analyzed, then combined back and displayed.
Execution Sample
Matplotlib
import matplotlib.pyplot as plt
import numpy as np
img = plt.imread('image.png')
red = img[:,:,0]
plt.imshow(red, cmap='Reds')
plt.show()
This code loads an image, extracts the red channel, and displays it using a red color map.
Execution Table
StepActionVariableValue/Result
1Load imageimg3D array shape (height, width, 3) with RGB values
2Extract red channelred2D array shape (height, width) with red values
3Display red channelplt.imshow(red, cmap='Reds')Image shown with red intensities
4End-Image display complete
💡 Image displayed and process ends
Variable Tracker
VariableStartAfter Step 1After Step 2Final
imgundefined3D array with RGB3D array with RGB3D array with RGB
redundefinedundefined2D array red channel2D array red channel
Key Moments - 2 Insights
Why do we use img[:,:,0] to get the red channel?
Because the image array stores colors in the last dimension as [Red, Green, Blue], so index 0 selects the red values (see execution_table step 2).
Why does plt.imshow(red, cmap='Reds') show a red image?
Because we tell matplotlib to use the 'Reds' color map, which colors the grayscale red channel data in shades of red (see execution_table step 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the shape of 'red' after step 2?
A2D array with red channel values
B3D array with 3 color channels
C1D array with pixel values
DScalar value
💡 Hint
Check the 'Variable' and 'Value/Result' columns in step 2 of execution_table
At which step is the image actually shown on screen?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for plt.imshow and plt.show actions in execution_table
If we want to extract the blue channel, which index should we use?
A1
B2
C0
D3
💡 Hint
Recall RGB channels are indexed as 0=Red, 1=Green, 2=Blue (see key_moments question 1)
Concept Snapshot
Color channel handling:
- Images are arrays with shape (height, width, 3)
- Channels: 0=Red, 1=Green, 2=Blue
- Extract channel: img[:,:,channel_index]
- Display single channel with plt.imshow(channel, cmap='ColorMap')
- Combine channels back with np.stack or similar
Full Transcript
We start by loading an image as a 3D array with RGB channels. Then we extract one color channel by selecting the appropriate slice in the last dimension. For example, img[:,:,0] gives the red channel. We can display this channel using matplotlib's imshow with a color map like 'Reds' to see the intensity of red in the image. This process helps us analyze or modify individual color channels before combining them back to form a full color image.