Here is an example code to generate transparent shape on image. Need to pay attention can not use cv::Mat mask(mat) to create the mask image, because mask will be just a shallow copy of mat.
int GenerateTransparentMask() { Mat mat = imread("test.jpg"); if (mat.empty()) return -1; Size size = mat.size(); cv::Mat mask ( size, mat.type() ); mat.copyTo(mask); //cv::Mat mask(mat); //Can not work, becuase mask will be just a copy of mat, if draw on mask, means draw on mat too Rect rect(100, 100, 100, 100); rectangle(mask, rect, Scalar(0, 0, 255), CV_FILLED, CV_AA, 0); double alpha = 0.3; double beta = 1.0 - alpha; cv::addWeighted(mask, alpha, mat, beta, 0.0, mat); cvNamedWindow("Result"); imshow("Result", mat); cvWaitKey(0); //wait for a key press return 0; }
The result will as below:
If you need to generate complicated mask on an image, need to use a little different method. Below is the example code.
int GenerateTransparentMask() { const Mat mat = imread("DetectingContours.jpg"); if (mat.empty()) return -1; imshow("origianl", mat); Size size = mat.size(); cv::Mat copy ( size, mat.type() ); mat.copyTo ( copy ); //cv::Mat mask(mat); //Can not work, becuase mask will be just a copy of mat, draw on mask, means draw on mat too cv::Mat mask(size, CV_8U); //mask must be CV_8U mask.setTo(Scalar(0)); Rect rect(200, 100, 200, 200); rectangle(mask, rect, Scalar(255, 255, 255), CV_FILLED, CV_AA, 0); rectangle(mask, Rect(280, 120, 40, 40), Scalar(0, 0, 0), CV_FILLED); circle(mask, Point(300, 220), 30, Scalar(0), CV_FILLED); copy.setTo(Scalar(0, 0, 255), mask); //imshow("copy", copy); double alpha = 0.5; double beta = 1.0 - alpha; cv::Mat result(size, mat.type()); cv::addWeighted(copy, alpha, mat, beta, 0.0, result); cvNamedWindow("Result"); imshow("Result", result); cvWaitKey(0); //wait for a key press return 0; }