Subscribe & download the code for the article "Bitwise Operations and Image Masking with OpenCV".
(You'll need to confirm your subscription to get the code)