Search code examples
python-3.xopencvimage-processingcomputer-visionscikit-image

overlay one part of image onto another image


There are two corresponding images, the second one reflects the mask area of the first one.

the first image enter image description here

How to over lay the red area in the second image onto the first image?


Solution

  • You can do it with OpenCV like this:

    #!/usr/local/bin/python3
    
    import numpy as np
    import cv2
    
    # Load base image and overlay
    base = cv2.imread("image.jpg",   cv2.IMREAD_UNCHANGED)
    over = cv2.imread("overlay.jpg", cv2.IMREAD_UNCHANGED)
    
    # Anywhere the red channel of overlay image exceeds 127, make base image red
    # Remember OpenCV uses BGR ordering, not RGB
    base[over[...,2]>127] = [0,0,255]
    
    # Save result
    cv2.imwrite('result.jpg',base)
    

    enter image description here


    If you wanted to blend a small percentage of red (say 20%) while retaining the structure of the underlying image, you could do this:

    #!/usr/local/bin/python3
    
    import numpy as np
    import cv2
    
    # Load base image and overlay
    base = cv2.imread("image.jpg",   cv2.IMREAD_UNCHANGED)
    over = cv2.imread("overlay.jpg", cv2.IMREAD_UNCHANGED)
    
    # Blend 80% of the base layer with 20% red
    blended = cv2.addWeighted(base,0.8,(np.zeros_like(base)+[0,0,255]).astype(np.uint8),0.2,0)
    
    # Anywhere the red channel of overlay image exceeds 127, use blended image, elsewhere use base
    result = np.where((over[...,2]>127)[...,None], blended, base)
    
    # Save result
    cv2.imwrite('result.jpg',result)
    

    enter image description here


    By the way, you don't actually need any Python, you can just do it in Terminal with ImageMagick like this:

    magick image.jpg \( overlay.jpg -fuzz 30% -transparent blue \) -composite result.png
    

    enter image description here


    Keywords: Python, image processing, overlay, mask.