Want transparent image even after blending

前端 未结 1 845
暗喜
暗喜 2020-12-22 05:16

I am trying to blend two images as shown here.

This is my whole code

#include 
#include 
#include 

usin         


        
相关标签:
1条回答
  • 2020-12-22 05:52

    You can blend only pixels that have alpha channel greater than 0, with a custom loop. I think that the code is more clear than an explanation:

    #include <opencv2\opencv.hpp>
    #include <iostream>
    
    using namespace cv;
    using namespace std;
    
    int main()
    {
        Mat3b bkg = imread("path_to_girl_image");
        Mat4b fgd = imread("path_to_necklace_image", IMREAD_UNCHANGED);
    
        int x = 150;
        int y = 500;
        double alpha = 0.5; // alpha in [0,1]
    
        Mat3b roi = bkg(Rect(x, y, fgd.cols, fgd.rows));
    
        for (int r = 0; r < roi.rows; ++r)
        {
            for (int c = 0; c < roi.cols; ++c)
            {
                const Vec4b& vf = fgd(r,c);
                if (vf[3] > 0) // alpha channel > 0
                {
                    // Blending
                    Vec3b& vb = roi(r,c);
                    vb[0] = alpha * vf[0] + (1 - alpha) * vb[0];
                    vb[1] = alpha * vf[1] + (1 - alpha) * vb[1];
                    vb[2] = alpha * vf[2] + (1 - alpha) * vb[2];
                }
            }
        }
    
        imshow("Girl with necklace", bkg);
        waitKey();
    
        return 0;
    }
    

    Result:

    0 讨论(0)
提交回复
热议问题