让蒙面区域透明?

时间:2015-02-10 07:38:47

标签: c++ opencv transparent image-manipulation mask

到目前为止,我已设法使用蒙版并从第一张图片中获取第二张图片。但我想要的是第二个图像中的黑色区域是透明的(即我试图得到的输出是第三个图像)这是到目前为止的代码。请告诉我这个。

编辑:第三个来自photoshop

    //imwrite parameters
compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
compression_params.push_back(100);

//reading image to be masked
image = imread(main_img, -1);

//CV_LOAD_IMAGE_COLOR

namedWindow("output", WINDOW_NORMAL);
//imshow("output", image);

//Creating mask image with same size as original image
Mat mask(image.rows, image.cols, CV_8UC1, Scalar(0));


// Create Polygon from vertices
ROI_Vertices.push_back(Point2f(float(3112),float(58)));
ROI_Vertices.push_back(Point2f(float(3515),float(58)));
ROI_Vertices.push_back(Point2f(float(3515),float(1332)));
ROI_Vertices.push_back(Point2f(float(3112),float(958)));

approxPolyDP(ROI_Vertices, ROI_Poly, 1, true);

// Fill polygon white
fillConvexPoly(mask, &ROI_Poly[0] , ROI_Poly.size(), 255, 8, 0);                 

//imshow("output", mask);

// Create new image for result storage
imageDest = cvCreateMat(image.rows, image.cols, CV_8UC4);

// Cut out ROI and store it in imageDest
image.copyTo(imageDest, mask);

imwrite("masked.jpeg", imageDest, compression_params);
imshow("output", imageDest);

cvWaitKey(0);   

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

这可以通过首先将其alpha值设置为要使其完全透明的区域的0(其他区域为255),然后将其保存到PNG来完成。

要设置pixel-(x,y)的alpha值,可以这样做:

image.at<cv::Vec4b>(y, x)[3] = 0;

PS:如果当前没有图像,则需要先将其转换为4通道格式。例如:

cv::cvtColor(image, image, CV_BGR2BGRA);

更新:如果您已经计算了ROI区域的掩码,那么您可以更容易地将其与原始图像合并(假设有3个通道)以获得最终结果。像:

cv::Mat mask; // 0 for transparent regions, 255 otherwise (serve as the alpha channel)

std::vector<cv::Mat> channels;
cv::split(image, channels);

channels.push_back(mask);
cv::Mat result;
cv::merge(channels, result);