Applyingv a 2D mask onto a 3D rgb color list
Problem
I have the following image data as a 3D numpy array containing rgb values of the image in a (n,n,3) shaped list (Image). I also have data of the corresponding black and white mask image in a (n,n) list (Mask). The goal is to apply the Mask on the Image data, so that only rgb values corresponding to white mask areas are shown. 103
Python Image: (n,n,3) - Shape: (200,200,3) - Size: 120000 Mask: (n,n) - shape:(200,200) - size: 40000
My Idea was to broadcast/apply the mask on the image.. something like this: [ (n, n, 1) Image ~ Mask = (n, n, 3) * (n, n) = (n, n, 1) * [(n,n,1)] (n, n, 1) ]
Implementation
Mask data is represented as list of 0 and 255 values: ``` Mask
* shape: (200,200)
* size: 40000
* Values: [0, 0, 0] = black, [255, 255, 255] = white
array([[ 0, 0, 0, ..., 0, 0, 0], [ 0, 0, 0, ..., 0, 0, 0], [ 0, 0, 0, ..., 0, 0, 0], ..., [255, 255, 255, ..., 0, 0, 0], [255, 255, 255, ..., 0, 0, 0], [255, 255, 255, ..., 0, 0, 0]], dtype=uint8) The Image data is represented as list of rgb values: Image
* Shape: (200,200,3)
* Size: 120000
array([[[ 0, 0, 0], [ 0, 0, 0], [ 0, 0, 0], ..., [ 0, 0, 0], [ 0, 0, 0], [ 0, 0, 0]],
[[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
...,
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0]],
[[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
...,
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0]],
...,
[[189, 240, 247],
[227, 242, 242],
[207, 206, 207],
...,
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0]],
[[202, 254, 254],
[242, 255, 255],
[255, 255, 255],
...,
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0]],
[[163, 242, 255],
[161, 254, 255],
[213, 255, 255],
...,
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0]]], dtype=uint8)
``` Code to apply apply the mask:
```python import numpy as np from numpy import ma
def apply_mask( array: List[str], # Dict[str, np.ndarray], mask: List[str] # Dict[str, np.ndarray] ): """ Applies a list of boolean values (mask) to an array using indexing. This will return only the elements that satisfy a condition, where the mask contains 'True' or 1.
Libraries
---------
numpy as np
numpy.ma as ma
Parameters
----------
array : List[str]
The Array
mask: List[str]
The Mask
Returns
-------
masked_arr : List[str]
Filtered Array
Ex.
If you want to apply this mask = [[0,0,0,]
[0,1,1]
[1,1,1]]
on this array; arr = [[0,1,2], you would use:
[3,4,5],
[6,7,8]]
apply_mask(arr,mask) = [[-- -- --]
[-- 4 5]
[6 7 8]]
"""
masked_arr = ma.masked_array(array, np. 68