【问题标题】:Extracting transparent background of an image with opencv使用opencv提取图像的透明背景
【发布时间】:2014-11-30 17:16:28
【问题描述】:

我在grab_cut(计算前景)中计算了一个蒙版。我只想提取背景,使前景透明。我设法使用以下代码来提取前景(背景透明)。怎么可能反其道而行之?

int border = 20;
int border2 = border + border;
cv::Rect rectangle(border,border,image.cols-border2,image.rows-border2);

cv::Mat result; // segmentation result (4 possible values)
cv::Mat bgModel,fgModel; /
cv::grabCut(image,    // input image
    result,   // segmentation result
    rectangle,// rectangle containing foreground 
    bgModel,fgModel, // models
    1,        // number of iterations
    cv::GC_INIT_WITH_RECT); // use rectangle
cv::compare(result,cv::GC_PR_FGD,result,cv::CMP_EQ);
cv::Mat foreground(image.size(),CV_8UC3,cv::Scalar(255,255,255));
image.copyTo(foreground,result); // bg pixels not copied
cv::rectangle(image, rectangle, cv::Scalar(255,255,255),1);
cv::imwrite(argv[2], foreground);
cv::imwrite(argv[3], image);

Mat dst;//(src.rows,src.cols,CV_8UC4);
Mat tmp,alpha;

cvtColor(foreground,tmp,CV_BGR2GRAY);
threshold(tmp,alpha,100,255,THRESH_BINARY);
Mat rgb[3];
split(foreground,rgb);
Mat rgba[4]={rgb[0],rgb[1],rgb[2],alpha};
merge(rgba,4,dst);
imwrite("dst.png",dst);

基本上我认为我必须改变这些行:

cv::Mat foreground(image.size(),CV_8UC3,cv::Scalar(255,255,255));
image.copyTo(foreground,result); // bg pixels not copied

如何选择与结果相反的图像的其余部分?

【问题讨论】:

    标签: opencv background foreground


    【解决方案1】:

    只需反转你的面具,如下所示:

    cv::Mat background(image.size(),CV_8UC3,cv::Scalar(255,255,255));
    image.copyTo(background, ~result); // fg pixels not copied
    

    【讨论】:

      猜你喜欢
      • 2016-12-08
      • 1970-01-01
      • 2021-03-29
      • 2016-11-27
      • 1970-01-01
      • 2019-10-02
      • 2011-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多