Bird
0
0

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📝 Application Q15 of 15
Matplotlib - Image Display
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?
Agray = img.mean(axis=2)
Bgray = img.mean(axis=0)
Cgray = img[:, :, 0] + img[:, :, 1] + img[:, :, 2]
Dgray = img.sum(axis=1)
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Matplotlib Quizzes