OpenCV - GrabCut with custom foreground/background models

前端 未结 2 856
深忆病人
深忆病人 2021-01-03 04:21

I want to use the GrabCut algorithm implemented on OpenCV.

As shown in the documentation this is the function signature:

void grabCut(
    InputArra         


        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-03 04:54

    Even I had a similar problem. This is how I solved it. I edited the GC_EVAL condition in the grabcut source code to this -

    if( mode == GC_EVAL )
       { checkMask( img, mask );
        for( int i = 0; i < iterCount; i++ )
    {
        GCGraph graph;
        assignGMMsComponents( img, mask, bgdGMM, fgdGMM, compIdxs );
    
        constructGCGraph(img, mask, bgdGMM, fgdGMM, lambda, leftW, upleftW, upW, uprightW, graph );
        estimateSegmentation( graph, mask );
        return;    
    }
    }
    

    Notice that the function learnGMMs is not called here. This is done because the Foreground and Background GMMs are precomputed.

    You can save models in a .xml file using the following code snippet.

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

    You can retrieve the models using the following code.

    FileStorage fs1("mymodels.xml", FileStorage::READ);
    
            fs1["BgdModel"] >> bgdModel1;
    
            fs1["FgdModel"] >> fgdModel1;
    

    This worked for me.

提交回复
热议问题