Last modified: Apr 21, 2025 By Alexander Williams

Python Basic Image Overlay Techniques

Image overlays combine two or more images into one. Python makes it easy with libraries like OpenCV and PIL. This guide covers basic techniques.

What Is Image Overlay?

Image overlay places one image over another. It can create effects like watermarks or composites. Python provides simple ways to achieve this.

For more advanced transformations, see our Python Image Perspective Correction Guide.

Required Libraries

You need OpenCV and PIL for these examples. Install them using pip:


pip install opencv-python pillow

Basic Overlay Using PIL

The Python Imaging Library (PIL) offers simple overlay methods. Use Image.blend() for transparency effects.


from PIL import Image

# Open base and overlay images
base = Image.open("base.jpg")
overlay = Image.open("overlay.png")

# Resize overlay to match base if needed
overlay = overlay.resize(base.size)

# Blend images with 50% transparency
result = Image.blend(base, overlay, alpha=0.5)
result.save("output.jpg")

Note: Both images must be the same size. Use resize() if needed.

Overlay with OpenCV

OpenCV provides more control. Use cv2.addWeighted() for weighted combinations.


import cv2

# Read images
base = cv2.imread("base.jpg")
overlay = cv2.imread("overlay.png")

# Resize overlay
overlay = cv2.resize(overlay, (base.shape[1], base.shape[0]))

# Apply overlay with weights
result = cv2.addWeighted(base, 0.7, overlay, 0.3, 0)
cv2.imwrite("output.jpg", result)

This gives 70% weight to the base and 30% to the overlay.

Positioning Overlays

You can place overlays at specific positions. This example puts a logo at the bottom-right.


import cv2

base = cv2.imread("base.jpg")
logo = cv2.imread("logo.png")

# Get positions
h, w = logo.shape[:2]
y = base.shape[0] - h - 10
x = base.shape[1] - w - 10

# Place logo
base[y:y+h, x:x+w] = logo
cv2.imwrite("output.jpg", base)

Adjust the coordinates to position your overlay.

Transparency with Alpha Channels

PNG images can have transparency. Use cv2.cvtColor() to handle alpha channels.


import cv2

base = cv2.imread("base.jpg")
overlay = cv2.imread("overlay.png", cv2.IMREAD_UNCHANGED)

# Split overlay into color and alpha
overlay_img = overlay[:,:,:3]
alpha = overlay[:,:,3] / 255.0

# Resize
overlay_img = cv2.resize(overlay_img, (base.shape[1], base.shape[0]))
alpha = cv2.resize(alpha, (base.shape[1], base.shape[0]))

# Blend
result = base.copy()
for c in range(3):
    result[:,:,c] = (1 - alpha) * base[:,:,c] + alpha * overlay_img[:,:,c]

cv2.imwrite("output.jpg", result)

This preserves the overlay's transparency.

Conclusion

Python makes image overlays simple with OpenCV and PIL. You can blend, position, and handle transparency easily.

For more image techniques, check our Python Image Mosaics Guide or Python Image Collages Guide.

Experiment with different weights and positions to create unique effects.