Bird
Raised Fist0
Matplotlibdata~20 mins

Color channel handling in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Color Channel Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of color channel extraction
What is the shape and data type of the red channel extracted from this RGB image array?
Matplotlib
import numpy as np
image = np.array([[[255, 0, 0], [0, 255, 0]],
                  [[0, 0, 255], [255, 255, 0]]], dtype=np.uint8)
red_channel = image[:, :, 0]
print(red_channel.shape, red_channel.dtype)
A(2, 2) uint8
B(2, 2, 3) uint8
C(3, 2) int32
D(2, 2) float64
Attempts:
2 left
💡 Hint
Remember that extracting one color channel from an RGB image reduces the last dimension.
data_output
intermediate
1:30remaining
Result of swapping color channels
Given an RGB image array, what is the resulting pixel value after swapping the red and blue channels for the pixel [100, 150, 200]?
Matplotlib
pixel = [100, 150, 200]
swapped_pixel = [pixel[2], pixel[1], pixel[0]]
print(swapped_pixel)
A[150, 100, 200]
B[100, 150, 200]
C[200, 100, 150]
D[200, 150, 100]
Attempts:
2 left
💡 Hint
Swapping red and blue means the first and last values switch places.
visualization
advanced
2:30remaining
Visualizing individual color channels
Which option correctly plots the green channel of an RGB image using matplotlib?
Matplotlib
import numpy as np
import matplotlib.pyplot as plt
image = np.random.randint(0, 256, (5, 5, 3), dtype=np.uint8)
green_channel = image[:, :, 1]
plt.imshow(green_channel, cmap='Greens')
plt.show()
Aplt.imshow(image[:, :, 1])
Bplt.imshow(image[:, :, 1], cmap='Greens')
Cplt.imshow(image[:, :, 1], cmap='Reds')
Dplt.imshow(image[:, :, 0], cmap='Greens')
Attempts:
2 left
💡 Hint
Use the correct channel index and a matching colormap for green.
🔧 Debug
advanced
2:00remaining
Identify the error in color channel normalization
What error will this code raise when normalizing the blue channel of an image?
Matplotlib
import numpy as np
image = np.array([[[10, 20, 30], [40, 50, 60]]], dtype=np.uint8)
blue_channel = image[:, :, 2]
normalized = blue_channel / 255
print(normalized.dtype)
ANo error; dtype is float64
BTypeError: unsupported operand type(s) for /: 'uint8' and 'int'
CValueError: operands could not be broadcast together
DAttributeError: 'numpy.ndarray' object has no attribute 'dtype'
Attempts:
2 left
💡 Hint
Dividing uint8 by int converts to float automatically.
🚀 Application
expert
3:00remaining
Calculate average intensity of red channel in an image
Given a 3x3 RGB image array, what is the average intensity of the red channel?
Matplotlib
import numpy as np
image = np.array([
  [[10, 20, 30], [40, 50, 60], [70, 80, 90]],
  [[15, 25, 35], [45, 55, 65], [75, 85, 95]],
  [[20, 30, 40], [50, 60, 70], [80, 90, 100]]
], dtype=np.uint8)
red_channel = image[:, :, 0]
avg_red = np.mean(red_channel)
print(round(avg_red, 2))
A40.0
B50.0
C45.0
D55.0
Attempts:
2 left
💡 Hint
Sum all red values and divide by 9 pixels.

Practice

(1/5)
1. What does the last dimension in a matplotlib image array usually represent?
easy
A. The image width
B. The image height
C. The color channels like red, green, and blue
D. The number of images in a batch

Solution

  1. Step 1: Understand image array structure

    Matplotlib images are stored as arrays where the last dimension holds color information.
  2. Step 2: Identify what the last dimension holds

    This last dimension typically contains the red, green, and blue channels for each pixel.
  3. Final Answer:

    The color channels like red, green, and blue -> Option C
  4. Quick Check:

    Last dimension = color channels [OK]
Hint: Remember: last dimension = RGB colors in image arrays [OK]
Common Mistakes:
  • Confusing width or height with the last dimension
  • Thinking the last dimension is batch size
  • Assuming grayscale images have 3 channels
2. Which of the following is the correct way to extract the green channel from a 3D image array named img in matplotlib?
easy
A. green = img[2, :, :]
B. green = img[1, :, :]
C. green = img[:, 1, :]
D. green = img[:, :, 1]

Solution

  1. Step 1: Recall channel indexing in image arrays

    Color channels are stored in the last dimension, with red=0, green=1, blue=2.
  2. Step 2: Extract green channel correctly

    To get green, select all rows and columns, but only index 1 in the last dimension: img[:, :, 1].
  3. Final Answer:

    green = img[:, :, 1] -> Option D
  4. Quick Check:

    Green channel index = 1 [OK]
Hint: Use img[:, :, 1] to get green channel [OK]
Common Mistakes:
  • Mixing up axis order and indexing rows or columns
  • Using wrong channel index for green
  • Selecting wrong dimensions
3. Given the code below, what will be the shape of red_channel?
import numpy as np
img = np.random.rand(100, 150, 3)
red_channel = img[:, :, 0]
medium
A. (100, 150)
B. (100, 150, 3)
C. (3, 100, 150)
D. (150, 3)

Solution

  1. Step 1: Understand original image shape

    img has shape (100, 150, 3) meaning 100 rows, 150 columns, 3 color channels.
  2. Step 2: Extract red channel shape

    Extracting img[:, :, 0] selects all rows and columns but only the first channel, so shape becomes (100, 150).
  3. Final Answer:

    (100, 150) -> Option A
  4. Quick Check:

    Channel extraction removes last dimension [OK]
Hint: Extracting one channel drops last dimension [OK]
Common Mistakes:
  • Expecting 3 channels after extraction
  • Confusing axis order
  • Misreading shape tuple
4. What is wrong with this code snippet that tries to swap the red and blue channels of an image array img?
img[:, :, 0] = img[:, :, 2]
img[:, :, 2] = img[:, :, 0]
medium
A. The syntax for slicing is invalid
B. It overwrites red channel before saving it, losing original data
C. The channel indices are incorrect for red and blue
D. It should use img[0, :, :] instead of img[:, :, 0]

Solution

  1. Step 1: Analyze channel swapping logic

    The code assigns blue channel to red, then red channel to blue without temporary storage.
  2. Step 2: Identify data overwrite problem

    After first line, original red data is lost, so second line copies new red (which is blue) back to blue channel.
  3. Final Answer:

    It overwrites red channel before saving it, losing original data -> Option B
  4. Quick Check:

    Swap needs temp variable to avoid overwrite [OK]
Hint: Use a temp variable when swapping channels [OK]
Common Mistakes:
  • Not using a temporary variable for swap
  • Mixing up channel indices
  • Incorrect slicing syntax
5. You want to create a grayscale image by averaging the red, green, and blue channels of an image array img. Which code correctly does this and keeps the result as a 2D array?
hard
A. gray = img.mean(axis=2)
B. gray = img.mean(axis=0)
C. gray = img[:, :, 0] + img[:, :, 1] + img[:, :, 2]
D. gray = img.sum(axis=1)

Solution

  1. Step 1: Understand axis for color channels

    Color channels are in the last dimension (axis=2) of img.
  2. Step 2: Average across color channels

    Using img.mean(axis=2) averages red, green, and blue for each pixel, resulting in a 2D array.
  3. Final Answer:

    gray = img.mean(axis=2) -> Option A
  4. Quick Check:

    Mean over axis=2 gives grayscale 2D image [OK]
Hint: Use mean(axis=2) to average RGB channels [OK]
Common Mistakes:
  • Averaging over wrong axis
  • Summing channels without dividing
  • Resulting in 3D array instead of 2D