Title: Transparent overlays with OpenCV - PyImageSearch

URL Source: https://pyimagesearch.com/2016/03/07/transparent-overlays-with-opencv/

Published Time: 2016-03-07T15:00:33+00:00

Markdown Content:
[![Image 1: transparent_overlay_animation](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20393'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2016/02/transparent_overlay_animation.gif)One of my favorite aspects of running the PyImageSearch blog is sharing _**little bitesize OpenCV tips and tricks**_ that I’ve learned after nearly _7 years_ of using the OpenCV library.

Today’s tip comes from my bag of experiences: **constructing transparent overlays with OpenCV**.

In order to construct a transparent overlay, you need two images:

1.  Your original image.
2.  An image containing what you want to “overlay” on top of the first using some level of alpha transparency.

The results of applying such a transparent overlay can see seen at the top of this blog post.

So, you might be wondering: _“When/where will I use a transparent overlay in my computer vision application? And why are you sharing this tip?”_

Great question.

For starters, if your OpenCV app requires a Heads-up Display (HUD) of any kind, you should consider using transparent overlays. Instead of displaying runtime critical information in _separate window_ or _in the terminal_, you can _**directly overlay**_ the information on your output image. Using transparent overlays alleviates the need to obfuscate the contents of the output image!

A second, more obvious example is alpha transparency where you need to “blend” two images together.

The use cases for transparent overlays are nearly endless — my goal in today’s blog post is simply to show you how you can incorporate them into your own applications.

![Image 2](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20128%20128'%3E%3C/svg%3E)

#### Looking for the source code to this post?

[Jump Right To The Downloads Section](#download-the-code)

In the remainder of this lesson, I’ll demonstrate how to construct transparent overlays using Python and OpenCV.

We’ll start with the following image:

[![Image 3: Figure 1: Our initial image that we are going to construct an overlay for.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20375'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2016/02/mexico.jpg)

**Figure 1:** Our initial image that we are going to construct an overlay for.

Our goal will be to:

*   Use the `cv2.rectangle` function to draw a red bounding box surrounding myself in the _bottom-right corner_ of the image.
*   Apply the `cv2.putText` method to draw the text `PyImageSearch` (along with the transparency factor) in the _top-left_ _corner_ of the image.

The results of drawing the rectangle and text can be seen below:

[![Image 4: Figure 2: Drawing a rectangle and text on the original image. However, both the text and bounding box are entirely opaque -- no transparency has been applied.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20393'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2016/02/transparent_overlay_10.jpg)

**Figure 2:** Drawing a rectangle and text on the original image. However, both the text and bounding box are entirely opaque — no transparency has been applied.

_**However, notice that both the rectangle and text are fully opaque!**_

You cannot see myself through the rectangle, nor does the “PyImageSearch” text contain any level of transparency.

To remedy this, we can leverage the `cv2.addWeighted` function to “blend” images together and construct the transparent overlay.

Let’s go ahead and dive into some source code to create a transparent overlay with Python and OpenCV. Open up a new file, name it `overlay.py` , and insert the following code:

\# 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:

1.  One for the final `output` image.
2.  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:

[![Image 5: Figure 3: Notice how for alpha=1.0, the text and rectangle are entirely opaque (i.e., not transparent).](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20393'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2016/02/transparent_overlay_10.jpg)

**Figure 3:** Notice how for _alpha=1.0_, the text and rectangle are entirely opaque (i.e., not transparent).

However, once we reach `alpha=0.5` , both the “PyImageSearch” text and rectangle are substantially more transparent:

[![Image 6: Figure 4: Constructing transparent overlays with Python and OpenCV.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20393'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2016/02/transparent_overlay_05.jpg)

**Figure 4:** Constructing transparent overlays with Python and OpenCV.

At `alpha=0.1` , the text and rectangle are barely visible:

[![Image 7: Figure 5: The smaller alpha gets, the more transparent the overlay will be.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20393'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2016/02/transparent_overlay_01.jpg)

**Figure 5:** The smaller _alpha_ gets, the more transparent the overlay will be.

Below you can see a GIF animation that visualizes each of the transparency levels:

[![Image 8: transparent_overlay_animation](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20393'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2016/02/transparent_overlay_animation.gif)

### What's next? We recommend [PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend).

**Course information:**  
84 total classes • 114+ hours of on-demand code walkthrough videos • Last updated: February 2024  
★★★★★ 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:**

*   ✓ **84 courses** on essential computer vision, deep learning, and OpenCV topics
*   ✓ **84 Certificates** of Completion
*   ✓ **114+ 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_ 536+ tutorials** on PyImageSearch
*   ✓ **Easy one-click downloads** for code, datasets, pre-trained models, etc.
*   ✓ **Access** on mobile, laptop, desktop, etc.

[Click here to join PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend)

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.

![Image 9](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20410%20567'%3E%3C/svg%3E)

#### 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!

![Image 10](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20240%20240'%3E%3C/svg%3E)

#### **About the Author**

Hi there, I’m Adrian Rosebrock, PhD. All too often I see developers, students, and researchers wasting their time, studying the wrong things, and generally struggling to get started with Computer Vision, Deep Learning, and OpenCV. I created this website to show you what I believe is the best possible way to get your start.