如何提供从一个图像到其他图像构造的前景和背景模型来执行Grabcut?

时间:2015-09-24 16:51:45

标签: c++ opencv

我正在使用opencv的grabcut.cpp和graphcut.cpp代码调用函数grabcut()。我必须找到一种方法来保存从某些图像计算出的背景和前景模型,并将其应用到另一个图像。如何保存'bgdmodel'和'fgdmodel'以备将来使用?

这是我写的代码 -

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <iostream>

using namespace std;
using namespace cv;

int main()
{

    // Load an image
    Mat img = imread("1.png",1);
    const Mat* img_0;
    img_0= &img;
    // Create the mask
    Mat mask;
    mask.create( img_0->size(), CV_8UC1);
    mask.setTo( GC_BGD );



    Mat bgdModel, fgdModel;
    Rect rect;
    rect.x=0;
    rect.y=0;
    rect.width=img.cols-1;
    rect.height=img.rows-1;
    (mask(rect)).setTo( Scalar(GC_BGD) );
    grabCut(img, mask, rect, bgdModel, fgdModel, 1, GC_INIT_WITH_RECT);


    // Save model to file

        FileStorage fs("mymodels.xml", FileStorage::WRITE);
        fs << "BgdModel" << bgdModel;
        fs << "FgdModel" << fgdModel;
        fs.release();



    // Load another image
    Mat img1 = imread( "abc.png", 1);
    const Mat* img_1;
    img_1= &img1;
    // Load models from file
    Mat bgdModel1, fgdModel1;
    Mat mask1;


        FileStorage fs1("mymodels.xml", FileStorage::READ);

        fs1["BgdModel"] >> bgdModel1;

        fs1["FgdModel"] >> fgdModel1;

        fs1.release();
    // Create a mask
    mask1.create( img_1->size(), CV_8UC1);
    mask1.setTo( GC_PR_FGD );
    Rect rect1;
    rect1.x=0;
    rect1.y=0;
    rect1.width=0;//img.cols;
    rect1.height=0;//img.rows;
    (mask1(rect1)).setTo( Scalar(GC_BGD) );


    grabCut(img1, mask1, rect1, bgdModel1, fgdModel1, 1, GC_EVAL);




   FileStorage fs2("finalmask.xml", FileStorage::WRITE);

        fs2 << "Final_MASK" << mask1;

        fs2.release();

     for (int i=0;i<img1.rows;i++)
     {
        for(int j=0;j<img1.cols;j++)
        {
            if(mask1.at<uchar>(i,j)==0||mask1.at<uchar>(i,j)==2)
            {
                img1.at<cv::Vec3b>(i,j)[0] = 0;
                img1.at<cv::Vec3b>(i,j)[1] = 0;
                img1.at<cv::Vec3b>(i,j)[2] = 0;
            }

        }
     }   


    imshow("Result of Grabcut", img1);
   waitKey(0);


return 0;
}

我需要确保为imagex学习的bgdModel和fgdModel也适用于image1。

1 个答案:

答案 0 :(得分:1)

您可以使用<link rel="stylesheet" id="theme" href="" type="text/css"> 保存背景和前景模型Mat,然后将其重新加载以用于下一张图片。

这个例子应该澄清这一点:

FileStorage