How do I find a set of all the unique elements that are in the mask of a masked numpy array?
For example, I have
seg = np.array([[1,2,3,4]])
mask = np.array([[False, True, False, True]])
How do I turn this into the set {2, 4}
?
CodePudding user response:
There are two ways to do this. If you have an array of type numpy.ma, which is the native numpy masked array class, you can flatten the masked array, then convert it to a list, and then a set:
y = ma.array(seg, mask=1-mask)
print(set(y.flatten().tolist()) - {None})
Which will print {2, 4}.
However, with how you've got it set up, the mask and the seg are in two separate numpy arrays. So you can do this:
boundaries = set(seg[np.where(mask)])
print(boundaries)
This finds the indexes where the mask is 1, gets the elements of seg at these indexes, and makes a set out of them.
edit: You can just use seg[mask] as per hpaulj's comment:
boundaries = set(seg[mask])
print(boundaries)
Which will print {2, 4}.
CodePudding user response:
In addition to @chenjesu's answer, you can also get a set [2 4]
instead of a numpy array with the following function:
def find_unique_elements(seg, mask):
# Find the unique elements in the mask of the masked array.
unique_elements = np.unique(seg[mask])
return unique_elements
in your case, this will return the [2 4]
set.