Here, you could use cv2.bitwise_and function if you already have the mask image.

For check the below code:

img = cv2.imread('lena.jpg')
mask = cv2.imread('mask.png',0)
res = cv2.bitwise_and(img,img,mask = mask)

The output will be as follows for a lena image, and for rectangular mask.

Answer from Abid Rahman K on Stack Overflow
🌐
PyImageSearch
pyimagesearch.com › home › blog › image masking with opencv
Image Masking with OpenCV - PyImageSearch
November 10, 2024 - You came to learn Computer Vision and basic masking, super! In this tutorial, you learned the basics of masking using OpenCV. The key point of masks is that they allow us to focus our computation only on regions of the image that interest us.
Top answer
1 of 5
110

Here, you could use cv2.bitwise_and function if you already have the mask image.

For check the below code:

img = cv2.imread('lena.jpg')
mask = cv2.imread('mask.png',0)
res = cv2.bitwise_and(img,img,mask = mask)

The output will be as follows for a lena image, and for rectangular mask.

2 of 5
39

Well, here is a solution if you want the background to be other than a solid black color. We only need to invert the mask and apply it in a background image of the same size and then combine both background and foreground. A pro of this solution is that the background could be anything (even other image).

This example is modified from Hough Circle Transform. First image is the OpenCV logo, second the original mask, third the background + foreground combined.

# http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html
import cv2
import numpy as np

# load the image
img = cv2.imread('E:\\FOTOS\\opencv\\opencv_logo.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# detect circles
gray = cv2.medianBlur(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 5)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=50, minRadius=0, maxRadius=0)
circles = np.uint16(np.around(circles))

# draw mask
mask = np.full((img.shape[0], img.shape[1]), 0, dtype=np.uint8)  # mask is only 
for i in circles[0, :]:
    cv2.circle(mask, (i[0], i[1]), i[2], (255, 255, 255), -1)

# get first masked value (foreground)
fg = cv2.bitwise_or(img, img, mask=mask)

# get second masked value (background) mask must be inverted
mask = cv2.bitwise_not(mask)
background = np.full(img.shape, 255, dtype=np.uint8)
bk = cv2.bitwise_or(background, background, mask=mask)

# combine foreground+background
final = cv2.bitwise_or(fg, bk)

Note: It is better to use the opencv methods because they are optimized.

🌐
GeeksforGeeks
geeksforgeeks.org › python › masking-in-python-opencv
Masking in Python OpenCV - GeeksforGeeks
February 13, 2026 - This approach works for both images and live video. 1. cv2.inRange(): This function creates a binary mask by selecting pixels that fall within a specified color range.
🌐
Medium
medium.com › @sasaniperera › opencv-object-masking-b3143e310d03
OpenCV: Object Masking. Object masking is very important in… | by Sasani Perera | Medium
August 14, 2023 - We need to change the range of Saturation and Value until we get a satisfactory mask. ... Almost there! Let’s fine-tune it more. ... Looks good!! So this is how we extract an object of a certain colour (range) from an image. ... #import necessary libraries import cv2 import numpy as np import matplotlib.pyplot as plt #using opencv to read an image #BGR Image plate_image_1 = cv2.imread("C:/users/public/pictures/numberp_1.png") #converting BGR to HSV HSV_im_1 = cv2.cvtColor(plate_image_1,cv2.COLOR_BGR2HSV) #defining HSV range Orange_UB = np.array([40,255,245]) Orange_LB = np.array([20,55,180]) #masking mask = cv2.inRange(HSV_im_1,Orange_LB,Orange_UB) #visualizing cv2.namedWindow("HSV Orange masked", cv2.WINDOW_NORMAL); cv2.imshow("HSV Orange masked",mask); cv2.waitKey(0) & 0xFF cv2.destroyAllWindows()
🌐
OpenCV
docs.opencv.org › 4.13.0 › d7 › d37 › tutorial_mat_mask_operations.html
OpenCV: Mask operations on matrices
Prev Tutorial: How to scan images, lookup tables and time measurement with OpenCV Next Tutorial: Operations with images · Mask operations on matrices are quite simple. The idea is that we recalculate each pixel's value in an image according to a mask matrix (also known as kernel).
🌐
DigitalOcean
digitalocean.com › community › tutorials › arithmetic-bitwise-and-masking-python-opencv
Image Processing Part 5: Arithmetic, Bitwise, and Masking | DigitalOcean
Technical tutorials, Q&A, events — This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-mask-an-image-in-opencv-python
How to mask an image in OpenCV Python?
March 26, 2026 - OpenCV Python Server Side Programming Programming · We can apply a mask to an image by computing the cv2.bitwise_and() between the mask and the image. To track a color, we define a mask in HSV color space using cv2.inRange() passing lower and ...
🌐
Automatic Addison
automaticaddison.com › how-to-apply-a-mask-to-an-image-using-opencv
How to Apply a Mask to an Image Using OpenCV
November 17, 2019 - Usage: image_masking.py [<image>] Keys: r - mask the image SPACE - reset the inpainting mask ESC - exit ''' # Python 2/3 compatibility from __future__ import print_function import cv2 # Import the OpenCV library import numpy as np # Import Numpy library import matplotlib.pyplot as plt # Import ...
Find elsewhere
🌐
OpenCV
forum.opencv.org › python
How to mask an image (when mask, actually, hides the portion of the image - not highlights it)? - Python - OpenCV
July 27, 2022 - Hello dear OpenCV community. I’ve been following this tutorial to create a mask. You can see how his “mask” leaves only his face and removes the rest of the image. I want exactly the opposite: to hide the face and leave…
🌐
YouTube
youtube.com › watch
Learn How to apply image masking in opencv in 8 mins | Opencv Tutorial - YouTube
Welcome to DWBIADDA's computer vision ( OpenCV ) tutorial, as part of this lecture we are going to learn,Learn How to apply image masking in opencv
Published: January 18, 2021
🌐
Medium
mcazarez.medium.com › applying-a-mask-to-images-and-videos-in-python-using-opencv-83ef46a4e5e4
Applying a Mask to Images and Videos in Python Using OpenCV | by Manny Salazar | Medium
January 20, 2024 - This is particularly crucial when the camera feed includes elements that can interfere with analysis, like in wildlife monitoring scenarios. In this guide, we’ll explore how to apply a mask to both images and videos using Python and OpenCV, ensuring that our algorithms focus only on the relevant areas.
🌐
FreedomVC
freedomvc.com › home › image › opencv › image thresholding
Image Thresholding and Masks with OpenCV - FreedomVC
June 6, 2021 - Image thresholding allows us to create an image mask by applying a “threshold” to determine whether each pixel is of interest to us or not.
🌐
YouTube
youtube.com › data magic (by sunny kusawa)
Image Masking using OpenCV l Mask Image | Computer Vision | Data Magic - YouTube
Hello Friends, Here is an new computer vision episode on How to mask image.We are going to conver RGB color image into HSV image and after that will create a...
Published: November 6, 2020
Views: 22K
🌐
Idiot Developer
idiotdeveloper.com › home › image masking with opencv addweighted
Image Masking with OpenCV AddWeighted - Idiot Developer
August 15, 2024 - Here’s the syntax of the addWeighted function in OpenCV: dst = cv2.addWeighted(src1, alpha, src2, beta, gamma) ... Now that we’ve covered the basics, let’s move on to image masking.
🌐
OpenCV
docs.opencv.org › 4.13.0 › db › d75 › samples_2cpp_2create_mask_8cpp-example.html
OpenCV: samples/cpp/create_mask.cpp
This program demonstrates using mouse events and how to make and use a mask image (black and white) .
🌐
Sifaelndandala
sifaelndandala.com › blog › masking-images-with-opencv
Masking Images with OpenCV | Sifael Blog Notes
February 7, 2022 - This technique can be used to separate ... ranges of pixel intensity. This example demonstrates masking of the following process. The OpenCV inRange() can be used to create a mask of an image....
🌐
GeeksforGeeks
geeksforgeeks.org › python › opencv-alpha-blending-and-masking-of-images
OpenCV - Alpha blending and masking of images - GeeksforGeeks
January 3, 2023 - We can create a black and white mask from an image with a transparent background. Python3 · import cv2 im = cv2.imread("spectacles.png", cv2.IMREAD_UNCHANGED) _, mask = cv2.threshold(im[:, :, 3], 0, 255, cv2.THRESH_BINARY) cv2.imwrite('mask.jpg', mask) Output: Create Quiz · Comment · S · soumibardhan10 · Follow · 0 · Improve · S · soumibardhan10 · Follow · 0 · Improve · Article Tags : Python · OpenCV ·
🌐
Medium
medium.com › @bhargavdora66 › understanding-opencv-masking-and-bluring-db5ab4573adc
Understanding OpenCV Masking And Bluring | by Bhargavdora | Medium
November 1, 2025 - # Step 1: Load image image = cv2.imread('apple.jpg')# Step 2: Create a circular mask mask = np.zeros(image.shape[:2], dtype=np.uint8) cv2.circle(mask, (150, 150), 100, 255, -1)# Step 3: Apply the mask masked_image = cv2.bitwise_and(image, image, mask=mask)# Step 4: Show results cv2.imshow('Original Image', image) cv2.imshow('Mask', mask) cv2.imshow('Masked Image', masked_image) cv2.waitKey(0) cv2.destroyAllWindows() ... Where LLL and UUU are the lower and upper bounds of color intensity. Understanding Image Smoothing in OpenCV — Mean, Median, Gaussian & Bilateral Filters