//First load your source image, here load as gray scale
cv::Mat srcImage = cv::imread("sourceImage.jpg", CV_LOAD_IMAGE_GRAYSCALE);

//Then define your mask image
cv::Mat mask = cv::Mat::zeros(srcImage.size(), srcImage.type());

//Define your destination image
cv::Mat dstImage = cv::Mat::zeros(srcImage.size(), srcImage.type());    

//I assume you want to draw the circle at the center of your image, with a radius of 50
cv::circle(mask, cv::Point(mask.cols/2, mask.rows/2), 50, cv::Scalar(255, 0, 0), -1, 8, 0);

//Now you can copy your source image to destination image with masking
srcImage.copyTo(dstImage, mask);

Then do your further processing on your dstImage. Assume this is your source image:

Then the above code gives you this as gray scale input:

And this is the binary mask you created:

And this is your final result after masking operation:

Answer from user5133845 on Stack Overflow
🌐
PyImageSearch
pyimagesearch.com › home › blog › image masking with opencv
Image Masking with OpenCV - PyImageSearch
November 10, 2024 - In this tutorial, you will learn how to mask images using OpenCV. My previous guide discussed bitwise operations, a very common set of techniques used heavily in image processing.
🌐
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()
Top answer
1 of 2
30
//First load your source image, here load as gray scale
cv::Mat srcImage = cv::imread("sourceImage.jpg", CV_LOAD_IMAGE_GRAYSCALE);

//Then define your mask image
cv::Mat mask = cv::Mat::zeros(srcImage.size(), srcImage.type());

//Define your destination image
cv::Mat dstImage = cv::Mat::zeros(srcImage.size(), srcImage.type());    

//I assume you want to draw the circle at the center of your image, with a radius of 50
cv::circle(mask, cv::Point(mask.cols/2, mask.rows/2), 50, cv::Scalar(255, 0, 0), -1, 8, 0);

//Now you can copy your source image to destination image with masking
srcImage.copyTo(dstImage, mask);

Then do your further processing on your dstImage. Assume this is your source image:

Then the above code gives you this as gray scale input:

And this is the binary mask you created:

And this is your final result after masking operation:

2 of 2
4

Since you are looking for a clear circular center with a shape inside, you could use Hough Transform to get that area- a careful selection of parameters will help you get this area perfectly.

A detailed tutorial is here: http://docs.opencv.org/doc/tutorials/imgproc/imgtrans/hough_circle/hough_circle.html

For setting pixels outside a region black:

Create a mask image : cv::Mat mask(img_src.size(),img_src.type());

Mark the points inside with white color :

cv::circle( mask, center, radius, cv::Scalar(255,255,255),-1, 8, 0 );

You can now use bitwise_AND and thus get an output image with only the pixels enclosed in mask.

cv::bitwise_and(mask,img_src,output);

🌐
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
🌐
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
🌐
GeeksforGeeks
geeksforgeeks.org › python › opencv-invert-mask
OpenCV - Invert Mask - GeeksforGeeks
January 3, 2023 - Now to invert this mask, we perform bitwise not operation on each value, that is, 0 changes to 1 and vice versa: ... To invert a mask in OpenCV, we use the cv2.bitwise_not() function, which performs bitwise not operation on individual pixels.
Find elsewhere
🌐
OpenCV
docs.opencv.org › 4.13.0 › d7 › d37 › tutorial_mat_mask_operations.html
OpenCV: Mask operations on matrices
You use the mask by putting the center of the mask matrix (in the upper case noted by the zero-zero index) on the pixel you want to calculate and sum up the pixel values multiplied with the overlapped matrix values. It's the same thing, however in case of large matrices the latter notation is a lot easier to look over. ... You can download this source code from here or look in the OpenCV source code libraries sample directory at samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp.
🌐
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>] ... # Date created: 9/18/2019 # Python version: 3.7 # Description: This program allows users to highlight a specific # object within an image by masking it....
🌐
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 › what-is-masking-an-image-in-opencv
What is masking an image in OpenCV?
April 13, 2020 - Using this method you can mask or filter an image. import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.highgui.HighGui; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class MaskingExample { public static void main( String[] args ) { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Reading the input image String file = "D://images//boy.jpg"; Mat src = Imgcodecs.imread(file); //Creating an empty matrix to store the result Mat dst = new Mat(); //Creating kernel1 Mat kernel1 =
🌐
OpenCV Q&A Forum
answers.opencv.org › question › 96817 › how-to-create-mask-from-an-image-in-opencv
How to create mask from an image in opencv? - OpenCV Q&A Forum
June 19, 2016 - this is the image from which i want create mask of the face of cat( i.e including eyes , nose , mouth ) or like if i want to create the mask only for the ears i want to create mask for : ... #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" using namespace cv; using namespace std; Mat src,cloneimg; bool mousedown; vector<vector<Point> > contours; vector<Point> pts; void onMouse( int event, int x, int y, int flags, void* userdata ) { Mat img = *((Mat *)userdata); if( event == EVENT_LBUTTONDOWN ) { mousedown = true; contours.clear(); pts.clear(); } if( event == EVENT_LBUTTONUP ) { mo
🌐
Medium
avaz-asgarov.medium.com › masking-objects-by-color-contour-in-opencv-a-step-by-step-guide-d3220ead03f8
Masking Objects by Color & Contour in OpenCV: A Step-by-Step Guide | by Avaz Asgarov | Medium
May 1, 2025 - Apply the refined mask to the RGB image def_mask = cv2.bitwise_and(img_rgb, img_rgb, mask=can_mask) Lines 5–8: Read the image and prepare both RGB and HSV versions. Lines 10–13: Select an HSV range suitable for isolating the can’s colors.
🌐
YouTube
youtube.com › watch
OpenCV - Masking & Bitwise Operations
To learn more, please visit the YouTube Help Center: https://www.youtube.com/help
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.

🌐
GitHub
github.com › ArunJayan › OpenCV-Python › blob › master › masking.py
OpenCV-Python/masking.py at master · ArunJayan/OpenCV-Python
cv2.waitKey(0) #we readed the image · · mask = np.zeros(img.shape[:2],dtype="uint8") (cx,cy) = (img.shape[1]/2,img.shape[0]/2) cv2.rectangle(mask,(cx-75,cy-75),(cx+75,cy+75),255,-1) cv2.imshow("Mask",mask) cv2.waitKey(0) ·
Author: ArunJayan
🌐
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.