To replace a part of image

import cv2
import numpy as np

img1 = cv2.imread('Desert.jpg')
img2 = cv2.imread('Penguins.jpg')

img3 = img1.copy()
# replace values at coordinates (100, 100) to (399, 399) of img3 with region of img2
img3[100:400,100:400,:] = img2[100:400,100:400,:]
cv2.imshow('Result1', img3)

To alpha blend two images

alpha = 0.5
img3 = np.uint8(img1*alpha + img2*(1-alpha))
cv2.imshow('Result2', img3)

Answer from user8190410 on Stack Overflow
๐ŸŒ
TheAILearner
theailearner.com โ€บ 2019 โ€บ 03 โ€บ 26 โ€บ image-overlays-using-bitwise-operations-opencv-python
Image Overlays using Bitwise Operations OpenCV-Python | TheAILearner
March 26, 2019 - So, using these simple bitwise operations we can overlay an image to another. Be careful while creating the mask as it entirely depends on the image.
๐ŸŒ
Master Data Science
datahacker.rs โ€บ 012-blending-and-pasting-images-using-opencv
#012 Blending and Pasting Images Using OpenCV - Master Data Science
January 5, 2021 - To successfully apply this process in OpenCV we need to select Region of Interest (ROI) in the first image, and then apply masking and some logical operations to overlay second image over the first image.
Discussions

overlay a smaller image on a larger image python OpenCv - Stack Overflow
Hi I am creating a program that replaces a face in a image with someone else's face. However, I am stuck on trying to insert the new face into the original, larger image. I have researched ROI and More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Using openCV to overlay/blend transparent image onto another image - Stack Overflow
How can I overlay a transparent PNG onto another image without losing it's transparency using openCV in python? More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - overlay image on another image with opencv and numpy - Stack Overflow
i have two images, i need to use numpy and opencv to overlay foreground on top of background using numpy masks. import numpy as np import cv2 import matplotlib.pyplot as plt background = cv2.imread(& More on stackoverflow.com
๐ŸŒ stackoverflow.com
October 18, 2021
python - Overlay image on another image opencv - Stack Overflow
I want to overlay the object in a smaller image (transparent background) to the larger one but turns out it has the black dotted lines at the border of overlay objects. I did google search and found this overlay image on another image with opencv and numpy but still, it has the problem that ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
December 9, 2021
๐ŸŒ
PyImageSearch
pyimagesearch.com โ€บ home โ€บ blog โ€บ transparent overlays with opencv
Transparent overlays with OpenCV - PyImageSearch
April 17, 2021 - 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)
๐ŸŒ
GitHub
github.com โ€บ pydemo โ€บ overlay
GitHub - pydemo/overlay: Overlay 2 images using python and OpenCV ยท GitHub
#OVERLAY OPACITY = 0.7 added_image = cv2.addWeighted(new_background,0.6,square,0.4,0) cv2.imshow('adjusted', added_image) cv2.waitKey() cv2.imwrite(out, added_image)
Author: pydemo
Top answer
1 of 9
181

A simple way to achieve what you want:

import cv2
s_img = cv2.imread("smaller_image.png")
l_img = cv2.imread("larger_image.jpg")
x_offset=y_offset=50
l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img

Update

I suppose you want to take care of the alpha channel too. Here is a quick and dirty way of doing so:

s_img = cv2.imread("smaller_image.png", -1)

y1, y2 = y_offset, y_offset + s_img.shape[0]
x1, x2 = x_offset, x_offset + s_img.shape[1]

alpha_s = s_img[:, :, 3] / 255.0
alpha_l = 1.0 - alpha_s

for c in range(0, 3):
    l_img[y1:y2, x1:x2, c] = (alpha_s * s_img[:, :, c] +
                              alpha_l * l_img[y1:y2, x1:x2, c])

2 of 9
28

Using @fireant's idea, I wrote up a function to handle overlays. This works well for any position argument (including negative positions).

def overlay_image_alpha(img, img_overlay, x, y, alpha_mask):
    """Overlay `img_overlay` onto `img` at (x, y) and blend using `alpha_mask`.

    `alpha_mask` must have same HxW as `img_overlay` and values in range [0, 1].
    """
    # Image ranges
    y1, y2 = max(0, y), min(img.shape[0], y + img_overlay.shape[0])
    x1, x2 = max(0, x), min(img.shape[1], x + img_overlay.shape[1])

    # Overlay ranges
    y1o, y2o = max(0, -y), min(img_overlay.shape[0], img.shape[0] - y)
    x1o, x2o = max(0, -x), min(img_overlay.shape[1], img.shape[1] - x)

    # Exit if nothing to do
    if y1 >= y2 or x1 >= x2 or y1o >= y2o or x1o >= x2o:
        return

    # Blend overlay within the determined ranges
    img_crop = img[y1:y2, x1:x2]
    img_overlay_crop = img_overlay[y1o:y2o, x1o:x2o]
    alpha = alpha_mask[y1o:y2o, x1o:x2o, np.newaxis]
    alpha_inv = 1.0 - alpha

    img_crop[:] = alpha * img_overlay_crop + alpha_inv * img_crop

Example usage:

import numpy as np
from PIL import Image

# Prepare inputs
x, y = 50, 0
img = np.array(Image.open("img_large.jpg"))
img_overlay_rgba = np.array(Image.open("img_small.png"))

# Perform blending
alpha_mask = img_overlay_rgba[:, :, 3] / 255.0
img_result = img[:, :, :3].copy()
img_overlay = img_overlay_rgba[:, :, :3]
overlay_image_alpha(img_result, img_overlay, x, y, alpha_mask)

# Save result
Image.fromarray(img_result).save("img_result.jpg")

Result:

If you encounter errors or unusual outputs, please ensure:

  • img should not contain an alpha channel. (e.g. If it is RGBA, convert to RGB first.)
  • img_overlay has the same number of channels as img.
๐ŸŒ
GitConnected
levelup.gitconnected.com โ€บ how-to-approach-image-overlay-problems-ad2d4a8e22bc
How to approach image overlay problems | by Shaurya Agarwal | Level Up Coding
December 14, 2021 - Similarly, if youโ€™d change the pixel values to [255, 0, 0], that area would become BLUE (OpenCV reads the images in BGR format). ... Similarly, those pixel values can be replaced by another image, just by using the pixel values of that image. In order to do that, you must reshape the overlaying image to the size whose pixels values you want to replace.
Find elsewhere
๐ŸŒ
Gary Sieling
garysieling.com โ€บ home โ€บ overlay one part of an image on another in opencv with python
Overlay one part of an image on another in OpenCV with Python - Gary Sieling
June 13, 2018 - Since these are just big arrays, you can copy one chunk of an image over another: frame[0:h, 0:w] = frame[y:y+h, x:x+w]
๐ŸŒ
GitHub
gist.github.com โ€บ 4260425
Overlay an image in OpenCV using Python ยท GitHub
Overlay an image in OpenCV using Python. GitHub Gist: instantly share code, notes, and snippets.
๐ŸŒ
Iditect
iditect.com โ€บ faq โ€บ python โ€บ combining-two-images-with-opencv-in-python.html
Combining Two Images with OpenCV in python
Description: This query focuses on pasting one image onto another image at a specified position (x, y coordinates) using OpenCV in Python, often used for image composition or annotation. ... import cv2 # Load images background_image = cv2.imread('background.jpg') overlay_image = cv2.imread...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 70295194 โ€บ overlay-image-on-another-image-opencv
python - Overlay image on another image opencv - Stack Overflow
December 9, 2021 - -- now, what you need is to erode the alpha channel. just a cv2.erode call with None kernel and one iteration should see improvement ... Yes, indeed the result is better and quite satisfactory. Thanks for that! ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Developers remain willing but reluctant to use AI: The 2025 Developer Survey... ... Stack Overflow chat opening up to all users in January; Stack Exchange chat... 1 overlay image on another image with opencv and numpy
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ image overlay onto opencv video
r/learnpython on Reddit: Image overlay onto opencv video
November 5, 2021 - I was doing some image masking and studies with opencv and was wondering how I could overlay an image over the video in real time, as I was searching I came across this code using cv2.addWeighted which helped me somewhat
๐ŸŒ
TheAILearner
theailearner.com โ€บ 2019 โ€บ 03 โ€บ 18 โ€บ add-image-to-a-live-camera-feed-using-opencv-python
Add image to a live camera feed using OpenCV-Python | TheAILearner
September 3, 2019 - OpenCV has a built-in function that does the exact same thing as shown below ยท The idea is that first, we will select which image we want to overlay (another image will serve as the background).
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 6122688 โ€บ overlay-two-images โ€บ 6124203
opencv - Overlay two images - Stack Overflow
First I created an image of a checkerboard pattern, and then I used this as a mask whilst using: cvAddS(one, cvScalar(0), dst, mask); cvNot(mask, mask); cvAddS(two, cvScalar(0), dst, mask); That seems to work!