Now after I deal with all this Python, OpenCV, Numpy thing for a while, I find out it's quite simple to implement this with code:

image[mask] = (0, 0, 255)

-------------- the original answer --------------

I solved this by the following code:

redImg = np.zeros(image.shape, image.dtype)
redImg[:,:] = (0, 0, 255)
redMask = cv2.bitwise_and(redImg, redImg, mask=mask)
cv2.addWeighted(redMask, 1, image, 1, 0, image)
Answer from Will Li on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › transparent-overlays-with-python-opencv
Transparent overlays with Python OpenCV - GeeksforGeeks
July 23, 2025 - import cv2 import numpy as np # Loading our images # Background/Input image background = cv2.imread('Assets/img1.jpg') # Overlay image overlay_image = cv2.imread('Assets/overlay3.png') # Resize the overlay image to match the bg image dimensions overlay_image = cv2.resize(overlay_image, (1000, 1000)) h, w = overlay_image.shape[:2] # Create a new np array shapes = np.zeros_like(background, np.uint8) # Put the overlay at the bottom-right corner shapes[background.shape[0]-h:, background.shape[1]-w:] = overlay_image # Change this into bool to use it as mask mask = shapes.astype(bool) # We'll create
Discussions

python - OpenCV overlay 2 image based on image mask - Stack Overflow
I need overlay 2 images based on third image mask Example 1.-I have this background 2.-I have this object image and also i have de segmentation image Object image I'm try to merge Backgound and O... More on stackoverflow.com
🌐 stackoverflow.com
opencv - How to overlay an image with another that has transparency using Python with OpenCv2 - Stack Overflow
Note: this solution uses the alpha channel as a binary mask. it does not blend pixel values. 2021-12-31T21:56:41.943Z+00:00 ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Are you learning with AI? We want to know about it! ... 2 Overlaying an image with another non-rectangular image containing black pixels using OpenCV in Python... More on stackoverflow.com
🌐 stackoverflow.com
How to use image masking to crop around a complex image? - Python - OpenCV
Hi all, I am attempting to crop around the image of this car below to acquire a transparent background: image 1 Using an approach developed in here I have been able to acquire a silhouette of the car as shown below: image 2 Using the following script I try to create a mask by turning the greyscale ... More on forum.opencv.org
🌐 forum.opencv.org
1
February 3, 2022
python - overlaying the ground truth mask on an image - Stack Overflow
In my project, I extracted frames from a video and in another folder I have ground truth for each frame. I want to map the ground truth image of each frame of a video (in my case, it is saliency More on stackoverflow.com
🌐 stackoverflow.com
🌐
OpenCV
forum.opencv.org › python
Overlaying image to mask - Python - OpenCV
March 29, 2022 - Hi everyone, How can i overlay an image to mask area ? How can i adjust transform as same.
🌐
TheAILearner
theailearner.com › 2019 › 03 › 26 › image-overlays-using-bitwise-operations-opencv-python
Image Overlays using Bitwise Operations OpenCV-Python | TheAILearner
March 26, 2019 - I created a customized function based on this, that also takes position as input, maybe it will be useful for someone: def occlusion(img: np.ndarray, occlusion_img: np.ndarray, pos: tuple[int, int]): result = img.copy() x, y = pos[1], pos[0] _, mask = cv2.threshold(occlusion_img, 254, 255, cv2.THRESH_BINARY)
🌐
Idiot Developer
idiotdeveloper.com › home › overlay mask on image using opencv in python
Overlay Mask on Image using OpenCV in Python - Idiot Developer
July 1, 2025 - Loads the original image and the RGB segmentation mask. Calls the overlay_mask_on_image() function with alpha = 0.6 to blend.
🌐
Note.nkmk.me
note.nkmk.me › home › python › opencv
Alpha blending and masking of images with Python, OpenCV, NumPy | note.nkmk.me
May 14, 2019 - See the section on alpha blending with NumPy below. Use cv2.bitwise_and() to do masking with OpenCV. ... cv2.bitwise_and() is a function that performs bitwise AND processing as the name suggests.
🌐
Medium
medium.com › the-owl › comprehensive-guide-to-overlaying-segmentation-masks-in-python-86b67dd93fad
Comprehensive Guide to Overlaying Segmentation Masks in Python | by Siladittya Manna | The Owl | Medium
May 30, 2025 - Alpha blending creates a semi-transparent overlay that allows the original image to show through the mask. This is particularly useful when you want to maintain context while visualising the segmentation.
Find elsewhere
🌐
Idiot Developer
idiotdeveloper.com › home › image masking with opencv addweighted
Image Masking with OpenCV AddWeighted - Idiot Developer
August 15, 2024 - We’ll start with a brief overview of how addWeighted works, followed by a step-by-step guide to masking an image using this function. The addWeighted function in OpenCV is primarily used to blend two images by applying a weighted sum. It’s widely used in various image processing tasks where smooth blending of two images is required, such as creating overlays, adjusting brightness, or mixing multiple images to achieve the desired effect.
🌐
PyImageSearch
pyimagesearch.com › home › blog › image masking with opencv
Image Masking with OpenCV - PyImageSearch
November 10, 2024 - To learn how to perform image masking with OpenCV, just keep reading. ... In the first part of this tutorial, we’ll configure our development environment and review our project structure. We’ll then implement a Python script to mask images with OpenCV.
🌐
GeeksforGeeks
geeksforgeeks.org › python › opencv-alpha-blending-and-masking-of-images
OpenCV - Alpha blending and masking of images - GeeksforGeeks
January 3, 2023 - We display and save the image as alpha_{image}.png. To continue and try out more alpha values, press 1. Else press 0 to exit. ... import cv2 img1 = cv2.imread('gfg.png') img2 = cv2.imread('apple.jpeg') img2 = cv2.resize(img2, img1.shape[1::-1]) cv2.imshow("img 1",img1) cv2.waitKey(0) cv2.imshow("img 2",img2) cv2.waitKey(0) choice = 1 while (choice) : alpha = float(input("Enter alpha value")) dst = cv2.addWeighted(img1, alpha , img2, 1-alpha, 0) cv2.imwrite('alpha_mask_.png', dst) img3 = cv2.imread('alpha_mask_.png') cv2.imshow("alpha blending 1",img3) cv2.waitKey(0) choice = int(input("Enter 1 to continue and 0 to exit"))
🌐
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 - When handling image and video ... such as on-screen icons or overlays. 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 ...
🌐
GitHub
github.com › xictus77 › Facial-mask-overlay-with-OpenCV-Dlib › blob › master › facial_mask.py
Facial-mask-overlay-with-OpenCV-Dlib/facial_mask.py at master · xictus77/Facial-mask-overlay-with-OpenCV-Dlib
# Using Python OpenCV – cv2.fillPoly() method to fill mask · # change parameter [mask_type] and color_type for various combination · img3 = cv2.fillPoly(img2, [mask_type[choice2]], choice1, lineType=cv2.LINE_AA) · · # cv2.imshow("image with mask outline", img2) ·
Author: xictus77
🌐
PyImageSearch
pyimagesearch.com › home › blog › transparent overlays with opencv
Transparent overlays with OpenCV - PyImageSearch
April 17, 2021 - This tutorial demonstrates how to use OpenCV to create transparent overlays with the cv2.addWeighted function and OpenCV + Python bindings.
🌐
Medium
medium.com › mlearning-ai › facial-mask-overlay-with-opencv-dlib-4d948964cc4d
Facial mask overlay with OpenCV-dlib | by Wong Chow Mein | Medium
October 7, 2020 - This library has been created using ... C/C++, Python, and Java. We will start by importing the necessary libraries required to perform digital overlaying of face mask: OpenCV, dlib, numpy, os and imutils. The next step is to initiate the colors of the face masks and also to set up the directory and path from which the images are to be ...
🌐
LearnOpenCV
learnopencv.com › home › object detection › using facial landmarks for overlaying faces with masks
Using Facial Landmarks for Overlaying Faces with Masks
May 5, 2021 - After applying the mentioned functions we have a new mask image the same size as the original one, with which we should overlay the original image. Since we’re using a mask image in .png format, it has a transparent alpha channel, which we use to merge both images into one.
🌐
OpenCV
forum.opencv.org › python
How to use image masking to crop around a complex image? - Python - OpenCV
February 3, 2022 - Hi all, I am attempting to crop around the image of this car below to acquire a transparent background: image 1 Using an approach developed in here I have been able to acquire a silhouette of the car as shown below: image 2 Using the following script I try to create a mask by turning the greyscale silhouette into a binary silhouette, which can be overlayed upon the original. import matplotlib.pyplot as plt from matplotlib.pyplot import imread import cv2 import numpy as np from PIL import I...
🌐
Kaggle
kaggle.com › code › purplejester › showing-samples-with-segmentation-mask-overlay
Showing Samples with Segmentation Mask Overlay
Checking your browser before accessing www.kaggle.com · Click here if you are not automatically redirected after 5 seconds
Top answer
1 of 2
8

I need to do similar things pretty often. In my favorite StackOverflow fashion, here is a script that you can copy and paste. I hope the code itself is self-explanatory. There are a few things that you can tune and try (e.g., color maps, overlay styles). It uses multiprocessing.Pool for faster batch-processing, resizes the mask to match the shape of the image, assumes the mask is in .png format, and depends on the file structure that you posted.

import os
from os import path
import cv2
import numpy as np

from argparse import ArgumentParser
from multiprocessing import Pool


def create_overlay(image, mask):
    """
    image: H*W*3 numpy array
    mask: H*W numpy array
    If dimensions do not match, the mask is upsampled to match that of the image

    Returns a H*W*3 numpy array
    """
    h, w = image.shape[:2]
    mask = cv2.resize(mask, dsize=(w,h), interpolation=cv2.INTER_CUBIC)

    # color options: https://docs.opencv.org/4.x/d3/d50/group__imgproc__colormap.html
    mask_color = cv2.applyColorMap(mask, cv2.COLORMAP_HOT).astype(np.float32)
    mask = mask[:, :, None] # create trailing dimension for broadcasting
    mask = mask.astype(np.float32)/255

    # different other options that you can use to merge image/mask
    overlay = (image*(1-mask)+mask_color*mask).astype(np.uint8)
    # overlay = (image*0.5 + mask_color*0.5).astype(np.uint8)
    # overlay = (image + mask_color).clip(0,255).astype(np.uint8)

    return overlay

def process_video(video_name):
    """
    Processing frames in a single video
    """
    vid_image_path = path.join(image_path, video_name)
    vid_mask_path = path.join(mask_path, video_name)
    vid_output_path = path.join(output_path, video_name)
    os.makedirs(vid_output_path, exist_ok=True)

    frames = sorted(os.listdir(vid_image_path))
    for f in frames:
        image = cv2.imread(path.join(vid_image_path, f))
        mask = cv2.imread(path.join(vid_mask_path, f.replace('.jpg','.png')), cv2.IMREAD_GRAYSCALE)
        overlay = create_overlay(image, mask)
        cv2.imwrite(path.join(vid_output_path, f), overlay)


parser = ArgumentParser()
parser.add_argument('--image_path')
parser.add_argument('--mask_path')
parser.add_argument('--output_path')
args = parser.parse_args()

image_path = args.image_path
mask_path = args.mask_path
output_path = args.output_path

if __name__ == '__main__':
    videos = sorted(
        list(set(os.listdir(image_path)).intersection(
                set(os.listdir(mask_path))))
    )

    print(f'Processing {len(videos)} videos.')

    pool = Pool()
    pool.map(process_video, videos)

    print('Done.')

Output:

EDIT: Made it work on Windows; changed pool.apply to pool.map.

2 of 2
4

This is not much different from @hkchengrex solution, so he deserves the credit, since his answer was first. I mainly wanted to point out the use of cv2.addWeighted

Here is one way to blend the image and ground truth in Python/OpenCV.

I would suggest resizing the ground truth once to the size of the images for all your video frames rather than resizing every video frame to the size of the ground truth.

One simple resizes the ground truth to the size of the image. Then colorize the ground truth using a color map. Then simply use cv2.addWeighted to blend the two for every frame of your video.

I leave it to you to read your video to access each frame. The following simply shows how to process any given frame

Input:

Ground Truth Overlay:

import cv2
import numpy as np

# read image
img = cv2.imread('bullfight.png')
hh, ww = img.shape[:2]

# read ground truth overlay
overlay = cv2.imread('truth.png')

# resize the overlay to match the size of the image
over_resize = cv2.resize(overlay, (ww,hh), fx=0, fy=0, interpolation=cv2.INTER_CUBIC)

# colorize the over_resized image
over_color = cv2.applyColorMap(over_resize, cv2.COLORMAP_HOT)

# blend over_color and image (adjust weights for different effects)
result = cv2.addWeighted(img, 1, over_color, 1, 0)

# save output image
cv2.imwrite('bullfight_overlay.png', result) 

# display images
cv2.imshow('overcolor', over_color)
cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result: