MATLAB: Masking out Image area using Binary Mask

binary mask and imageImage Processing Toolboxmasking

Hello
I have an image and I also have a binary mask of the same size(ROI in 1, Background 0). How can I create a new image only with the ROI displayed ?
Is there any difference if the image is grayscale plane or RGB ?
Thank you

Best Answer

Let I be the m-by-n image, and let M be the m-by-n mask.
The new image, Inew, will be m-by-n and have zeros everywhere there is a zero in M and will be the grayscale value wherever M has a one.
Inew = I.*M;
If the image is RGB (i.e. I is m-by-n-by-3), then use the command
Inew = I.*repmat(M,[1,1,3]);