Skip to content

Instantly share code, notes, and snippets.

@Brick85
Last active May 3, 2019 09:35
Show Gist options
  • Save Brick85/5009046 to your computer and use it in GitHub Desktop.
Save Brick85/5009046 to your computer and use it in GitHub Desktop.
OpenCV Alpha Blending: Blend two cv::Mat with alpha mask. Poorly optimised.
void blendWithMask(cv::Mat &base, cv::Mat &src, cv::Mat &mask, cv::Mat &out){
char ch = base.channels();
double alpha = 0;
for( int y = 0; y < base.rows; y++ ){
uchar* pBS = base.ptr<uchar>(y);
uchar* pSR = src.ptr<uchar>(y);
uchar* pMK = mask.ptr<uchar>(y);
uchar* pOU = out.ptr<uchar>(y);
for( int x = 0; x < base.cols*ch; x++ ){
int ix = x / ch;
if(pMK[ix] == 255){
pOU[x] = pBS[x];
} else if(pMK[ix] == 0){
pOU[x] = pSR[x];
} else {
alpha = pMK[ix] / 255.0;
pOU[x] = pSR[x] * (1-alpha) + pBS[x] * alpha;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment