You can use iterators to go through the input image and mask, and set appropriate values to pixels in the output image. An example which uses iterators.
If you don’t want to do that, you can threshold your input again, then do some operations on the two masks (multiply or subtract) to get the desired output. An example which uses a mask. A list of intensity-based filters.