Gradient mask blending in opencv python

前端 未结 3 578
[愿得一人]
[愿得一人] 2020-12-17 06:17

I have an image and circle zone. I need to blur all, except for circle zone. Also i need to make border of circle smooth.
The input:

The output(made it in image

3条回答
  •  渐次进展
    2020-12-17 06:50

    I think maybe you want something like that.

    This is the source image:

    The source-blured-pair :

    The mask-alphablened-pair:


    The code with description in the code comment.

    #!/usr/bin/python3
    # 2018.01.16 13:07:05 CST
    # 2018.01.16 13:54:39 CST
    import cv2
    import numpy as np
    
    def alphaBlend(img1, img2, mask):
        """ alphaBlend img1 and img 2 (of CV_8UC3) with mask (CV_8UC1 or CV_8UC3)
        """
        if mask.ndim==3 and mask.shape[-1] == 3:
            alpha = mask/255.0
        else:
            alpha = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)/255.0
        blended = cv2.convertScaleAbs(img1*(1-alpha) + img2*alpha)
        return blended
    
    img = cv2.imread("test.png")
    
    H,W = img.shape[:2]
    mask = np.zeros((H,W), np.uint8)
    cv2.circle(mask, (325, 350), 40, (255,255,255), -1, cv2.LINE_AA)
    mask = cv2.GaussianBlur(mask, (21,21),11 )
    
    blured = cv2.GaussianBlur(img, (21,21), 11)
    
    blended1 = alphaBlend(img, blured, mask)
    blended2 = alphaBlend(img, blured, 255- mask)
    
    cv2.imshow("blened1", blended1);
    cv2.imshow("blened2", blended2);
    cv2.waitKey();cv2.destroyAllWindows()
    

    Some useful links:

    1. Alpha Blending in OpenCV C++ : Combining 2 images with transparent mask in opencv

    2. Alpha Blending in OpenCV Python: Gradient mask blending in opencv python

提交回复
热议问题