HOWTO · Python
Image Masking in OpenCV
In this article, we will see how to perform image masking using Bitwise AND in OpenCV Python.
On this page
Image masking lets you keep part of an image and combine it with another image. In OpenCV, masking is built on the Bitwise AND operation: the cv.bitwise_and() function computes the per-element bitwise AND of two arrays, and an optional mask decides which pixels of that result land in the output.
This article walks through the standard masking workflow in Python. Using a car photo and a logo file, we prepare a region of interest (ROI), build a binary mask and its inverse from the logo, apply both masks, and composite the logo into the top-left corner of the car image.
How cv.bitwise_and() Applies a Mask
cv.bitwise_and() is a module-level function in the cv2 package, not a method on an image object. Its Python signature looks like this:
cv.bitwise_and(src1, src2[, dst[, mask]])
src1andsrc2are the two input arrays. They must have the same size and data type. To mask a single image, pass the same array for both.dstis an optional output array of the same size and type; when you omit it, the function allocates and returns the result.maskis an optional 8-bit single-channel array the same size as the sources. Wherever the mask holds a nonzero value, the output pixel issrc1 & src2; wherever the mask holds0, the output pixel is0. The mask therefore selects which pixels of the operation appear in the result — that selection is the whole idea of image masking.
Run this example, which calls cv.bitwise_and() when OpenCV is installed and performs the identical per-element AND with plain Python lists otherwise:
import importlib.util
if importlib.util.find_spec("cv2") is not None:
import cv2 as cv
import numpy as np
pixels = np.array([[200, 120, 60], [30, 90, 250]], dtype=np.uint8)
mask = np.array([[255, 255, 0], [0, 255, 255]], dtype=np.uint8)
result = cv.bitwise_and(pixels, pixels, mask=mask).tolist()
else:
pixels = [[200, 120, 60], [30, 90, 250]]
mask = [[255, 255, 0], [0, 255, 255]]
result = [[v & m for v, m in zip(pr, mr)] for pr, mr in zip(pixels, mask)]
print(result)
[[200, 120, 0], [0, 90, 250]]
Each pixel under a 255 mask value is kept; each pixel under a 0 mask value is cleared. In a real mask the values are produced by thresholding rather than written by hand, which is the next step.
Prepare the Image Region of Interest
The goal is to place the logo on the car image’s top-left corner, so the code reads both files and slices a matching region out of the car image:
car = cv.imread("car.jpg")andlogo = cv.imread("logo.png")load the images as BGR arrays.cv.imreadreturnsNonewhen a file fails to load, so check both results before going further.logo.shapereturns(rows, cols, channels); the first two entries give the logo’s dimensions.roi = car[0:rows, 0:cols]takes a NumPy view of the car image’s top-left corner that exactly matches the logo size. Because it is a view, writing the composite back intocar[0:rows, 0:cols]updates the original image.
The logo must fit inside the car image. If the logo is wider or taller than the photo, the slice silently shrinks and cv.bitwise_and(roi, roi, mask=mask_inv) later fails with a size mismatch because mask_inv is sized to the logo rather than the shrunken ROI, so resize the logo first or pick a placement that fits. Note also that cv.imread loads a PNG as a three-channel BGR image by default — the alpha channel is dropped — so the logo and the ROI end up with matching channel counts.
Build a Binary Mask for the Logo
Two masks come out of the logo: mask, which selects the logo’s own pixels, and mask_inv, which selects everything else.
gray_logo = cv.cvtColor(logo, cv.COLOR_BGR2GRAY)converts the logo to grayscale; see thecv.cvtColor()function for more on color conversion._, mask = cv.threshold(gray_logo, 10, 255, cv.THRESH_BINARY)produces the binary mask: pixels brighter than10become255and darker pixels become0. For a logo on a dark or black background this isolates the logo’s shape; tune the10to match your own background.mask_inv = cv.bitwise_not(mask)flips every bit, giving the complementary mask that selects the background region instead.
Combine the Logo and Region of Interest
With both masks ready, two masked ANDs split the work: cv.bitwise_and(roi, roi, mask=mask_inv) keeps the car background and blacks out the logo shape, while cv.bitwise_and(logo, logo, mask=mask) keeps only the logo pixels. cv.add() then sums the two results into the composite, which is written back into the car image.
The complete script below performs every step. When OpenCV or the image files are not present, it prints a short message and stops without a traceback:
import importlib.util
if importlib.util.find_spec("cv2") is None:
print("This example needs OpenCV installed: pip install opencv-python.")
raise SystemExit
import cv2 as cv
car = cv.imread("car.jpg")
logo = cv.imread("logo.png")
if car is None or logo is None:
print("car.jpg and logo.png must sit next to this script.")
raise SystemExit
rows, cols = logo.shape[:2]
if rows > car.shape[0] or cols > car.shape[1]:
print("The logo is larger than the car image; resize it first.")
raise SystemExit
roi = car[0:rows, 0:cols]
gray_logo = cv.cvtColor(logo, cv.COLOR_BGR2GRAY)
_, mask = cv.threshold(gray_logo, 10, 255, cv.THRESH_BINARY)
mask_inv = cv.bitwise_not(mask)
background = cv.bitwise_and(roi, roi, mask=mask_inv)
foreground = cv.bitwise_and(logo, logo, mask=mask)
composite = cv.add(background, foreground)
car[0:rows, 0:cols] = composite
cv.imwrite("car-with-logo.png", car)
print("Wrote car-with-logo.png")
The script saves the finished image with cv.imwrite() so it also runs on machines without a display; the display calls appear in the next section.
Inspect the Masking Result
The composite places the logo over the car’s top-left corner while the rest of the photo stays untouched:
To see what each stage produced, display or save the intermediates — cv.imshow("mask", mask), cv.imshow("mask_inv", mask_inv), cv.imshow("background", background), and cv.imshow("foreground", foreground) followed by cv.waitKey(0) show them on screen, while cv.imwrite() writes them to disk on headless machines. cv.imshow() needs a GUI display, which is why the script above saves files instead.
In mask you should see the logo’s white silhouette on black, and mask_inv is its mirror. background shows the car corner with the logo shape cut out, and foreground shows only the logo. That is the whole masking pattern: threshold once, apply cv.bitwise_and() twice, add the results, and the ROI carries the merged image.