PY-76

Apply a Spatial Mask to Every Channel

  • Medium
  • Image Masks
  • Python

Task

Write apply_mask(image, mask, fill_values). The image is a non-empty three-dimensional NumPy array with shape (height, width, channels), dtype uint8, and axes in that order. A spatial mask has shape (height, width) and dtype bool; one True cell names one pixel and therefore selects every channel at that pixel.

fill_values must be a one-dimensional sequence of one non-boolean integer per channel. Each value must be in 0..255. On success return (result, "ok"). result must be an independent uint8 array with the same shape: replace all channels at True pixels with the corresponding fill value, and leave every channel at False pixels unchanged. Do not modify or share writable memory with image.

For an invalid image, mask, or fill sequence, return (None, "invalid image"), (None, "invalid mask"), or (None, "invalid fill values") respectively. Validate those boundaries in that order.

Example

If the two-channel pixel at (0, 1) is selected and fill_values is [9, 200], that pixel becomes [9, 200]. An unselected pixel is copied unchanged, even when only one nearby pixel is selected.

Your implementation

You may import NumPy as np. Do not print, ask for input, or mutate an input.