簡體   English   中英

使用GrabCut提取背景圖像

[英]Extracting Background Image Using GrabCut

我有一個圖像(.jpg圖像),我想從原始圖像中提取背景。 我已經google了很多,但只找到了提取前景圖像的教程。

我從另一個stackoverflow問題中獲取了代碼。 代碼對我來說很好,我已成功提取前景(根據我的要求)。 現在我想從原始圖像中完全刪除此前景。 我希望它是這樣的: -

背景=原始圖像 - 前景

空的空間可以填充黑色或白色。 我怎樣才能做到這一點?

我嘗試過使用這種技術: -

Mat background = image2 - foreground;

但它給出了一個完整的黑色圖像。

碼:-

#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;
}

注意:我是一名opencv初學者,現在對它並不了解。 如果你能發布完整的代碼(根據我的要求)或者只是發布代碼行並告訴我這些代碼行放在哪里,我將非常感謝你。 謝謝。

PS這是我在StackOverflow.com上的第二個問題。 道歉......如果不遵守任何慣例。

它不是復制所有前景像素,而是復制所有不是前景的像素。 您可以使用~來取消掩碼:

image.copyTo(background,~result);

如果您//Get the pixels marked as likely background怎么辦?

// Get the pixels marked as likely background
cv::compare(result,cv::GC_PR_BGD,result,cv::CMP_EQ);

編輯 :上面的代碼缺少GC_BGD像素。 盡管給出了更有效的答案,但讓我們完成我們的開始:

// Get the pixels marked as background
cv::compare(result,cv::GC_BGD,result_a,cv::CMP_EQ);
// Get the pixels marked as likely background
cv::compare(result,cv::GC_PR_BGD,result_b,cv::CMP_EQ);
// Final results
result=result_a+result_b;

只是一個小小的建議, @ William的回答可以更簡潔地寫成:

result = result & 1;

為了得到二進制掩碼。

也許另一個例子有幫助,其中我假設圖像的中間部分肯定是前景。 所以試試這個鏈接。 在此輸入鏈接描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM