Sub topic 14
Semi-transparent overlays
This chapter covers how to blend a drawn shape into an image so the content underneath stays visible. It assumes you can read an image with cv2.imread, know that OpenCV stores pixels in BGR order, and have drawn shapes on a copy of an image. You should also be comfortable indexing NumPy arrays.
Why drawing functions cannot be transparent
OpenCV's drawing functions such as cv2.rectangle and cv2.circle have no opacity setting. They write the color you give them directly into the array and replace whatever pixels were there. A filled rectangle with thickness -1 hides everything under it.
To get a see-through highlight, you draw the shape on a separate copy of the image and then mix that copy with the original. Each output pixel becomes a weighted average of the two sources. This is called alpha blending, and cv2.addWeighted does it for whole arrays.
This builds on the previous chapter. Drawing on a copy is already the habit that keeps the original intact. Here the copy has a second job: it is the overlay layer.
The blending formula
For two images of the same size and type, cv2.addWeighted(src1, alpha, src2, beta, gamma) computes this for every pixel and channel:
dst = src1 * alpha + src2 * beta + gammaThe result is rounded and clipped to the valid range for the data type. For uint8 images, that range is 0 to 255.
| Argument | Meaning | Typical value |
|---|---|---|
| `src1` | First image, here the overlay | the drawn copy |
| `alpha` | Weight of the first image | 0.4 |
| `src2` | Second image, here the original | the untouched image |
| `beta` | Weight of the second image | `1 - alpha` |
| `gamma` | Constant added to every pixel | 0 |
When beta equals 1 - alpha and gamma is 0, the result is a plain weighted average. Pixels where the overlay and original are identical stay unchanged. Only the pixels you drew on change.
A first overlay
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
overlay = img.copy()
cv2.rectangle(overlay, (50, 50), (250, 200), (0, 255, 0), -1)
alpha = 0.4
blended = cv2.addWeighted(overlay, alpha, img, 1 - alpha, 0)
cv2.imwrite("blended.jpg", blended)Inside the rectangle, each pixel is 40% green and 60% original. Outside it, overlay and img hold the same values, so the weighted average gives back the original value. The green is (0, 255, 0) in BGR order, which is pure green.
The data flow looks like this:
Choosing alpha
Alpha is the opacity of the overlay layer.
alpha = 0.0gives the original image.alpha = 1.0gives the overlay at full strength, which looks like an ordinary opaque fill.- Values around 0.2 to 0.5 work well for highlights that must not hide detail.
Pick alpha by what the viewer needs to read. A dark red fill at 0.5 over a bright photo can still look heavy. A light yellow at 0.3 usually reads as a highlighter.
Blending only a region
The first example runs addWeighted on the whole image. That is simple, but it does extra work on pixels that did not change. For a large image with a small highlight, you can blend only the region of interest (ROI) that the shape covers.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
x1, y1, x2, y2 = 50, 50, 250, 200
alpha = 0.4
out = img.copy()
roi = out[y1:y2, x1:x2]
green = roi.copy()
green[:] = (0, 255, 0)
cv2.addWeighted(green, alpha, roi, 1 - alpha, 0, dst=roi)
cv2.imwrite("blended_roi.jpg", out)Several details matter here:
- Slicing is
[y1:y2, x1:x2], rows first. This is the reverse of the(x, y)order the drawing functions use. roiis a view intoout, as covered in the cropping chapter. Writing into it changesout.green[:] = (0, 255, 0)sets every pixel of the copy to one BGR color by broadcasting the tuple across the array.- Passing
dst=roiwrites the result straight into the view. That is whyoutchanges without an assignment.
The original img is untouched because out is a copy. If you had sliced img directly, the highlight would have been written into the original.
This approach works for rectangles. For circles or polygons, the bounding box is a rectangle but the shape is not, so you need the full-image method or a mask.
Blending a non-rectangular shape
For any filled shape, the full-image method works the same way. Only the drawing call changes.
import cv2
import numpy as np
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
points = np.array([[100, 50], [250, 80], [220, 200], [80, 180]], dtype=np.int32)
overlay = img.copy()
cv2.fillPoly(overlay, [points.reshape(-1, 1, 2)], (0, 255, 255))
cv2.circle(overlay, (150, 125), 30, (0, 0, 255), -1)
alpha = 0.35
blended = cv2.addWeighted(overlay, alpha, img, 1 - alpha, 0)
cv2.imwrite("blended_shapes.jpg", blended)Both shapes go on the same overlay layer, so one addWeighted call blends them together. Where the circle sits inside the polygon, the circle's color replaces the polygon's color on the overlay, and the blend then applies once. The two shapes are not blended with each other at partial opacity.
If you want each shape at a different opacity, use one overlay and one addWeighted call per shape, feeding each result into the next call as the base image.
Keeping text and outlines opaque
A common mistake is to draw a label on the overlay before blending. The text then fades along with the fill and can become hard to read.
Draw the text after blending, on the blended image:
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
overlay = img.copy()
cv2.rectangle(overlay, (50, 50), (250, 200), (0, 255, 0), -1)
alpha = 0.4
result = cv2.addWeighted(overlay, alpha, img, 1 - alpha, 0)
cv2.rectangle(result, (50, 50), (250, 200), (0, 180, 0), 2)
cv2.putText(result, "Region", (55, 45), cv2.FONT_HERSHEY_SIMPLEX,
0.8, (255, 255, 255), 2, cv2.LINE_AA)
cv2.imwrite("labeled_overlay.jpg", result)The outline and the label now sit on top at full strength. The order is: fill on the overlay, blend, then draw anything that must stay crisp.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| The highlight is fully opaque | `alpha` is 1.0, or the shape was drawn on `img` rather than on a copy | Draw on `overlay` and use `alpha` below 1 |
| The original image has a colored rectangle after saving | You drew on `img` directly | Call `img.copy()` before drawing |
| `error: (-209) sizes of input arguments do not match` | The two images have different shapes | Resize one to match the other, or use the same source |
| The image looks washed out or too dark | `alpha + beta` is not 1, or `gamma` is not 0 | Use `beta = 1 - alpha` and `gamma = 0` |
| Highlight color is the wrong hue | Color given in RGB order | Give colors as `(blue, green, red)` |
| Blended ROI is in the wrong place | Slice written as `[x, y]` | Use `[y1:y2, x1:x2]` |
| Text is faded | Text was drawn on the overlay | Draw text after `addWeighted` |
The size mismatch error also appears if one image was loaded in color and the other converted to grayscale. Both inputs need the same number of channels as well as the same width and height.
Edge cases
- Saturation.
addWeightedclips results to 0 to 255 foruint8. Ifalpha + betais above 1, bright areas clip to white. If you want to brighten on purpose, usegammaor a weight sum above 1, and expect clipping. - Grayscale images. Blending works on single-channel images too, but the fill color is then one number such as
255, not a tuple. - Transparency in PNG files.
cv2.imreaddrops the alpha channel by default and returns a 3-channel image. Reading withcv2.IMREAD_UNCHANGEDkeeps a fourth channel, butaddWeightedtreats it like any other channel and does not do compositing. Everything in this chapter is a manual blend of two opaque images. - Drawing on the overlay with
LINE_AA. Anti-aliased edges are themselves partial blends. On a filled overlay they still work, but the edge softness is further reduced byalpha. - Cost. Copying the image and blending it is cheap for typical photos. For video at high frame rates, blend the ROI only, and avoid allocating a new copy every frame if you can reuse a buffer.
Summary of the method
- Copy the image to make the overlay layer.
- Draw filled shapes on the overlay with thickness
-1, or withcv2.fillPoly. - Call
cv2.addWeighted(overlay, alpha, img, 1 - alpha, 0). - Draw outlines and text on the result so they stay opaque.
- Save or display the result.
Exercise
You draw a filled red circle on overlay = img.copy() and then run cv2.addWeighted(overlay, 0.25, img, 0.75, 0). What fraction of the circle's original-image color remains in the center of the circle, and why does the area outside the circle look unchanged?
Show answer
Inside the circle, each pixel is 25% red (the overlay) and 75% of the original pixel, so 75% of the original color remains. Outside the circle, the overlay and original pixels are identical, so 0.25 value + 0.75 value equals the original value.
Exercise
A colleague writes cv2.addWeighted(overlay, 0.5, img, 0.8, 0) and the result looks too bright. What is wrong, and what is the fix?
Show answer
The weights add up to 1.3, so each pixel is scaled above its original brightness and bright areas clip at 255. Use weights that sum to 1, for example beta = 1 - alpha, so cv2.addWeighted(overlay, 0.5, img, 0.5, 0).
Exercise
Write the slice that selects the rectangle from x = 40 to 140 and y = 10 to 60 in an image out, and say whether changing the slice also changes out.
Show answer
out[10:60, 40:140]. Rows (y) come first. The slice is a view, so writing into it, for example with cv2.addWeighted(..., dst=roi), changes out.