MATLAB: How to do masking with the help of binary image

binary imageImage Processing Toolboxmaskmasking

Hi,
I have a binary image and using that binary image I wish to do masking.
Here is the binary image:
Using this binary image I want to mask to the original Image.
Here is the original Image:
I want the output as :
So, the output image should have the binary image portion and the remaining should be black("0").
Can you suggest me the code to do this.
Thanks…

Best Answer

repmat your binary image across the three colour channels and use the invert of that as logical index into your colour image to set the pixels to 0:
colourmask = repmat(binarymask, [1 1 3]);
maskedimage = colourimage;
maskedimage(~colourmask) = 0;