Opencv: a combination of two images with an alpha mask

I am trying to combine two images with OpenCV as efficiently as possible. I currently have this:

// Input matrices to mix
cv::Mat A(w, h, CV_8UC3);
cv::Mat B(w, h, CV_8UC3);

// Mix factor
cv::Mat alpha(w, h, CV_8UC1);

// Have to multiply alpha channel for mul() function    
std::vector<cv::Mat> array{alpha, alpha, alpha};
cv::Mat alpha_multichannel;
cv::merge(array, alpha_multichannel);

cv::Mat result = A.mul(alpha_multichannel, 1./255) + B.mul(cv::Scalar(255, 255, 255) - alpha_multichannel, 1./255);

Currently, these are loops at least four times above the image (for the alpha_multichannel image, for A.mul, for B.mul and for the sum), although with a custom loop this can be done in one loop.

Is there a better way to do this?

+4
source share

Source: https://habr.com/ru/post/1599507/


All Articles