Bird
0
0

How can you correctly swap the red and blue channels of an RGB image array img using numpy without losing data?

hard📝 Application Q9 of 15
Matplotlib - Image Display
How can you correctly swap the red and blue channels of an RGB image array img using numpy without losing data?
Atemp = img[:, :, 0] img[:, :, 0] = img[:, :, 2] img[:, :, 2] = temp
Bimg[:, :, [0, 2]] = img[:, :, [2, 0]]
Cimg[:, :, 0], img[:, :, 2] = img[:, :, 2], img[:, :, 0]
Dimg[:, :, 0] = img[:, :, 2] img[:, :, 2] = img[:, :, 0]
Step-by-Step Solution
Solution:
  1. Step 1: Understand the problem

    Swapping red (channel 0) and blue (channel 2) requires temporarily storing one channel to avoid overwriting.
  2. Step 2: Analyze options

    temp = img[:, :, 0] img[:, :, 0] = img[:, :, 2] img[:, :, 2] = temp uses a temporary variable to hold red channel before assignment, ensuring no data loss.
  3. Step 3: Why others are incorrect

    img[:, :, [0, 2]] = img[:, :, [2, 0]] tries to assign slices simultaneously but numpy does not support this direct swapping. img[:, :, 0], img[:, :, 2] = img[:, :, 2], img[:, :, 0] attempts tuple unpacking which does not work for numpy arrays. img[:, :, 0] = img[:, :, 2] img[:, :, 2] = img[:, :, 0] overwrites red channel first, losing original data.
  4. Final Answer:

    Use a temporary variable to swap channels safely -> Option A
  5. Quick Check:

    Use temp variable to avoid overwriting [OK]
Quick Trick: Use temp variable to swap channels safely [OK]
Common Mistakes:
  • Overwriting one channel before saving it
  • Assuming tuple unpacking works on numpy slices
  • Trying to swap channels without temporary storage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Matplotlib Quizzes