使用GrabCut提取背景图像

Oma*_*riq 8 c++ opencv

我有一个图像(.jpg图像),我想从原始图像中提取背景.我已经google了很多,但只找到了提取前景图像的教程.

我从另一个stackoverflow问题中获取了代码.代码对我来说很好,我已成功提取前景(根据我的要求).现在我想从原始图像中完全删除此前景.我希望它是这样的: -

背景=原始图像 - 前景

空的空间可以填充黑色或白色.我怎样才能做到这一点?

我尝试过使用这种技术: -

Mat background = image2 - foreground;
Run Code Online (Sandbox Code Playgroud)

但它给出了一个完整的黑色图像.

码:-

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main( )
{
// Open another image
Mat image;
image= cv::imread("images/abc.jpg");

Mat image2 = image.clone();

// define bounding rectangle
cv::Rect rectangle(40,90,image.cols-80,image.rows-170);

cv::Mat result; // segmentation result (4 possible values)
cv::Mat bgModel,fgModel; // the models (internally used)

// GrabCut segmentation
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
cout << "oks pa dito" <<endl;
// Get the pixels marked as likely foreground
cv::compare(result,cv::GC_PR_FGD,result,cv::CMP_EQ);
// Generate output image
cv::Mat foreground(image.size(),CV_8UC3,cv::Scalar(255,255,255));
//cv::Mat background(image.size(),CV_8UC3,cv::Scalar(255,255,255));
image.copyTo(foreground,result); // bg pixels not copied

// draw rectangle on original image
cv::rectangle(image, rectangle, cv::Scalar(255,255,255),1);

imwrite("img_1.jpg",image);

imwrite("Foreground.jpg",foreground);
Mat background = image2 - foreground;
imwrite("Background.jpg",background);

return 0;
}
Run Code Online (Sandbox Code Playgroud)

注意:我是一名opencv初学者,现在对它并不了解.如果你能发布完整的代码(根据我的要求)或者只是发布代码行并告诉我这些代码行放在哪里,我将非常感谢你.谢谢.

PS这是我在StackOverflow.com上的第二个问题.道歉......如果不遵守任何惯例.

sie*_*hie 12

它不是复制所有前景像素,而是复制所有不是前景的像素.你可以通过使用~,否定掩码来做到这一点:

image.copyTo(background,~result);
Run Code Online (Sandbox Code Playgroud)