OpenCV-Python image fusion cv2.addWeighted weight addition function detailed explanation

☞ ░Go to LaoYuanPython blog https://blog.csdn.net/LaoYuanPython

I. Overview

In " OpenCV-Python image addition operation cv2.add function detailed explanation ", the image addition operation is introduced in detail. In addition to this addition, OpenCV also provides weighted addition, that is, when the pixel channel values ​​of the two images are added separately Add the values ​​according to a certain weight ratio.

Assuming that there are two image matrices src1 and src2, when the two images are fused, their respective weights are alpha and beta respectively, and the calculation formula for the channel value of each pixel in the target image dst after the two is fused is:

dst(I)=saturate(src1(I)∗alpha+src2(I)∗beta+gamma)

There is no mandatory requirement for the weights alpha and beta of the two images in the above formula, but it is generally recommended alpha+beta=1. In fact, the multiplication of alpha, beta and src1 and src2 is to adjust the brightness of the corresponding image of src1 and src2 (for this, please refer to " OpenCV-Python image multiplication operation cv2.multiply function detailed explanation and pixel value overflow normalization processing ") Therefore, the image fusion weight addition is actually to adjust the brightness of the two images before adding them.

If you have any questions about the above formula, please refer to:

Two, fusion cv2.addWeighted weight addition function syntax

Calling syntax:

addWeighted(src1, alpha, src2, beta, gamma, dst=None, dtype=None)

Parameter Description:
  • src1, src2: two images of equal size and number of channels that need to be merged and added
  • alpha: the weight of src1
  • beta: the weight of src2
  • gamma: gamma correction coefficient, no need to be corrected and set to 0, please refer to " Principle and Implementation Algorithm of Image Processing Gamma Correction (Gamma γ Correction) "
  • dst: Optional parameter, the variable for saving the output result, the default value is None, if it is not None, the output image is saved to the corresponding actual parameter of dst, and its size and channel number are the same as the input image. The depth of the image (that is, the image pixel Digits) confirmed by dtype parameter or input image
  • dtype: optional parameter, the depth of the output image array, that is, the number of bits of a single pixel value of the image (if RGB is represented by three bytes, it is 24 bits), the default value None means it is consistent with the source image.
  • Return value: the result image of fusion and addition

Three, case

addWeighted can only achieve the fusion and addition of two images of the same size. Perhaps what we need more is the fusion and addition of a small image and a large image. In this case, such a function is implemented:

def addWeightedSmallImgToLargeImg(largeImg,alpha,smallImg,beta,gamma=0.0,regionTopLeftPos=(0,0)):
    srcW, srcH = largeImg.shape[1::-1]
    refW, refH = smallImg.shape[1::-1]
    x,y =  regionTopLeftPos
    if (refW>srcW) or (refH>srcH):
        #raise ValueError("img2's size must less than or equal to img1")
        raise ValueError(f"img2's size {smallImg.shape[1::-1]} must less than or equal to img1's size {largeImg.shape[1::-1]}")
    else:
        if (x+refW)>srcW:
            x = srcW-refW
        if (y+refH)>srcH:
            y = srcH-refH
        destImg = np.array(largeImg)
        tmpSrcImg = destImg[y:y+refH,x:x+refW]
        tmpImg = cv2.addWeighted(tmpSrcImg, alpha, smallImg, beta,gamma)
        destImg[y:y + refH, x:x + refW] = tmpImg
        return destImg

The first 5 parameters of the addWeightedSmallImgToLargeImg function correspond to addWeighted, but there is an additional regionTopLeftPos parameter, which is used to specify the specific position where the upper left corner of the small image is placed on the large image. The default is the upper left corner of the large image.

Let's use addWeightedSmallImgToLargeImg to realize a case of fusion of two images. The large image seaside.jpg used in the case is as follows: the
Insert picture description here
small image beauty.jpg is as follows:
Insert picture description here
the two images are fused by weights of 100% and 10%, the code is as follows:

import numpy as np
import cv2

def main():
    img1 = cv2.imread(r'F:\pic\seaside.jpg')
    img2 = cv2.imread(r'F:\pic\beauty.jpg')
    img = addWeightedSmallImgToLargeImg(img1, 1, img2, 0.1,regionTopLeftPos=(300,300))
    cv2.imshow('img', img)
    cv2.waitKey(0)

main()

The fusion image displayed by the running result is as follows:

Insert picture description here

Four, summary

This article describes in detail the syntax of the cv2.addWeighted weight addition function for the fusion of two images of the same size and number of channels in OpenCV-Python, and implements a small image and a large image fusion function addWeightedSmallImgToLargeImg on this basis, and is implemented by addWeightedSmallImgToLargeImg A case of image fusion. It should be noted that there is no correlation between the weight coefficients of the two images fusion, but only used to set the brightness of the two images before fusion, but it is generally recommended that the sum of the two weight values ​​is 1.

For more information about OpenCV-Python, please refer to the related article in the column " OpenCV-Python Graphics and Image Processing ".

Paid column about the old ape

Lao Yuan’s paid column " Developing Graphical Interface Python Applications Using PyQt " specifically introduces the basic tutorials of PyQt graphical interface development based on Python, and the paid column " Moviepy Audio and Video Development Column " details the related methods and usage of moviepy audio and video editing and synthesis processing Method to process related editing and synthesis scenes. Both columns are suitable for novice readers who have a certain Python foundation but no relevant knowledge.

Paid column article catalog : " Moviepy audio and video development column article directory ", " Use PyQt to develop graphical interface Python application column directory ".

For those who lack Python foundation, you can learn Python from scratch through Lao Yuan’s free column " Column: Python Basic Tutorial Directory ".

If you are interested and willing to support the readers of Old Ape, welcome to buy paid columns.

Learn Python and OpenCV from the old ape!

☞ ░ to the old ape Python Bowen directory

Guess you like

Origin blog.csdn.net/LaoYuanPython/article/details/109143281