# import the necessary packages from __future__ import print_function import numpy as np import cv2 # load the image image = cv2.imread("mexico.jpg")
Lines 2-4 handle importing our required Python packages.
Line 7 loads our image from disk using the cv2.imread
function.
The next step is to loop over various values of alpha transparency between the range [0, 1.0], allowing us to visualize and understand how the alpha
value can influence our output image:
# loop over the alpha transparency values for alpha in np.arange(0, 1.1, 0.1)[::-1]: # create two copies of the original image -- one for # the overlay and one for the final output image overlay = image.copy() output = image.copy() # draw a red rectangle surrounding Adrian in the image # along with the text "PyImageSearch" at the top-left # corner cv2.rectangle(overlay, (420, 205), (595, 385), (0, 0, 255), -1) cv2.putText(overlay, "PyImageSearch: alpha={}".format(alpha), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3)
In order to apply the transparent overlay, we need to make two copies of the input image:
- One for the final
output
image. - And another for the
overlay
we are about to construct.
Using the cv2.rectangle
function, we draw a rectangle surrounding myself in the bottom-right corner of the image. We then apply cv2.putText
to draw the text PyImageSearch
in the top-left corner.
We are now ready to apply the transparent overlay using the cv2.addWeighted
function:
# apply the overlay cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output)
The cv2.addWeighted
method requires six arguments.
The first is our overlay
, the image that we want to “overlay” on top of the original image using a supplied level of alpha transparency.
The second parameter is the actual alpha transparency of the overlay. The closer alpha
is to 1.0, the more opaque the overlay will be. Similarly, the closer alpha
is to 0.0, the more transparent the overlay will appear.
The third argument to cv2.addWeighted
is the source image — in this case, the original image loaded from disk.
We supply the beta value as the fourth argument. Beta is defined as 1 - alpha
. We need to define both alpha and beta such that alpha + beta = 1.0
.
The fifth parameter is the gamma value — a scalar added to the weighted sum. You can think of gamma as a constant added to the output image after applying the weighted addition. In this case, we set it to zero since we do not need to apply an addition of a constant value.
Finally, we have the last argument, output
, which is the output destination after applying the weighted sum operation — this value is our final output image.
Our last code block handles displaying the final output image to our screen, as well as displaying the relevant alpha and beta values:
# show the output image print("alpha={}, beta={}".format(alpha, 1 - alpha)) cv2.imshow("Output", output) cv2.waitKey(0)
To execute our Python script, download the source code + example image to this post (using the “Downloads” form found at the bottom of this lesson) and execute the following command:
$ python overlay.py
You should see the following image displayed to your screen:
However, once we reach alpha=0.5
, both the “PyImageSearch” text and rectangle are substantially more transparent:
At alpha=0.1
, the text and rectangle are barely visible:
Below you can see a GIF animation that visualizes each of the transparency levels:
What's next? We recommend PyImageSearch University.
86+ total classes • 115+ hours hours of on-demand code walkthrough videos • Last updated: March 2025
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled
I strongly believe that if you had the right teacher you could master computer vision and deep learning.
Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?
That’s not the case.
All you need to master computer vision and deep learning is for someone to explain things to you in simple, intuitive terms. And that’s exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.
If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to successfully and confidently apply computer vision to your work, research, and projects. Join me in computer vision mastery.
Inside PyImageSearch University you'll find:
- ✓ 86+ courses on essential computer vision, deep learning, and OpenCV topics
- ✓ 86 Certificates of Completion
- ✓ 115+ hours hours of on-demand video
- ✓ Brand new courses released regularly, ensuring you can keep up with state-of-the-art techniques
- ✓ Pre-configured Jupyter Notebooks in Google Colab
- ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
- ✓ Access to centralized code repos for all 540+ tutorials on PyImageSearch
- ✓ Easy one-click downloads for code, datasets, pre-trained models, etc.
- ✓ Access on mobile, laptop, desktop, etc.
Summary
In this blog post, we learned how to construct transparent overlays using Python, OpenCV, and the cv2.addWeighted
function.
Future blog posts will use this transparent overlay functionality to draw Heads-up Displays (HUDs) on output images, and to make outputs more aesthetically appealing.
Download the Source Code and FREE 17-page Resource Guide
Enter your email address below to get a .zip of the code and a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!
Thanks for your consistent generosity!
Hi Adrian, first of all, thanks for all your contributions they’re just great.
At a first glance this might not look useful for somebody, but it is actually quite useful for several applications. One comment I have, would be, is there a way to apply transparent overlays of images that are different in size, and probably, in format? I.e. I have my pictures folder and I want to apply my watermark signature to all of them, but my watermark file is a .PNG with alpha channel enablled and no background (different size and format than JPEGS), you see what I mean? Seems the library requires that both of the images are equal in size and format.
Thank you very much
Kind regards
Both images do have to be the same size, but that’s easily accomplishable. The actual file format of the image doesn’t matter. Once the image is loaded via
cv2.imread
, an image is represented as a NumPy array, regardless of original image file type.In this case, I’m assuming your watermark is smaller than the original image? In that case, just clone the original image, place the watermark in image (using array slicing), and then apply the
cv2.addWeighted
method.Hey Adrian,
Thanks for sharing that! I looked for something like this for a long time, because I wanted my text displayed on the image to be more readable on every color…
I’m happy the code helped Linus! In a few short weeks I’ll be doing a post on using this same technique for creating watermarks with OpenCV. Be sure to take a look!
Hey Adrian,
Great post! Is there a way to overlay another image instead of a shape?
Absolutely. I’ll be covering that in next week’s blog post, so be sure to keep an eye out!
hi i want to overlay two images.
Could you give an example of what you’re trying to accomplish/build?
What would you do if you had to merge two images based on a varying alpha channel? Here, each pixel would have different alpha values. As far as I know, addweighted can only take alpha parameters for the whole image, not an alpha matrix, which is what I require.
I would instead do the weighted calculation using NumPy directly rather than
cv2.addWeighted
.There is a tutorial on how to do this at
Thanks for your blogs, the way to deliver the topic was so smooth and understandable. Thanks again
Thanks Slvgry, I appreciate that 🙂
Is there possible to draw multiple rectangles with the different opacity of each?
If I addWeighted multiple times than transparency of previous instances are lost because of multiple added picture… is there any workaround?
I have exactly the same requirement.. if you could find any workaround please do let me know.
Thanks in Advance
How can we do the similar thing but no overlay or blending, just making the image transparent with decrease in alpha and increase in beta same as in this code but on the image?
You’re referring to the image itself? You need to add an alpha channel to the image. This can be done by adding a new axis to the end of the image array.
Thank you for this awesome tutorial 🙂 May I ask, is it possible to save the transparent overlay as a separate mask image AFTER drawing? Like I’m trying to let the user sketch (by drawing continuous circles) on the original coloured image and the when the user is done, save only the drawings as a separate image mask. Please advise…Thank you!!
The
cv2.imwrite
function will allow you to write an output image to disk.It was a very helpful tutorial, Thanks to you for this. I am stuck in one point can you please help me out that is it possible that I draw a custom/external image over detected ball/color in this video? I mean to say that I want to detect a ball of green color and instead of masking it with the circle I want to draw an image over it and let it move as the ball move. Is there any code that could help me out? …. Thank you!
Hi Waqar — I’m not sure what you mean by “let it move as the ball moves”. Do you have an example of what you’re trying to achieve? That would be helpful in providing further suggestions.
Hi Adrian.
Thanks again for the article.
I have a problem with alpha channel images. While calculating the histogram of alpha channel image,OpenCV counts alpha channel as 0 (black) in all channels. We get a huge peak at zero. Is there any way to avoid reading alpha channel as zero value?
Thanks in advance
Hi Adrian, great article.
How would you handle overlaying more than 2 images over each other?
We know the cv2.addWeighted() function works well, but it only works for pairs of images (n=2).
What if you’re trying to superimpose 3 or 4 or more images together?
It doesn’t appear that cv2 has a function for this action.
Let’s say you have a list of 4 JPEG files that you want to overlay all onto a new single image file.
I was thinking you could iterate through the list and create an intermediate image that overlays the first two.
Then you could call addWeighted() again to add that intermediate and the 3rd image.
Then you could call that 2nd intermediate image to the 4th image using addWeighted() once again, and so on.
This seems like it would work, but there has to be a more elegant way of solving it.
How would one do this? Thanks
can you elaborate more on how to add an alpha channel to a three channel image?
Thank you so muuuuuuuuuuchhhhh !!!!!!!!!!!!!!!!!!!!!!!