天天看點

OpenCV3.0 Examples學習筆記(10)-grabcut.cpp-grabcut函數實作人機互動高效分割圖像前景背景

這個系列的目的是通過對OpenCV示例,進一步了解OpenCV函數的使用,不涉及具體原理。

目錄 簡介 Example運作截圖 Example分析 Example代碼

簡介

本文記錄了對OpenCV示例 grabcut .cpp 的分析。 資料位址: http://docs.opencv.org/3.0.0/de/dd0/grabcut_8cpp-example.html

這個示例主要示範了如何使用 grabcut對圖像進行分割。

示例涉及到

setMouseCallback, onMouse, grabCut等函數 具體如下:

setMouseCallback

為視窗建立滑鼠回調事件。

函數原型: void setMousecallback( const  string& winname, MouseCallback onMouse,  void * userdata=0)  

函數參數說明: winname:視窗的名字 onMouse:滑鼠響應函數,回調函數。指定視窗裡每次滑鼠時間發生的時候,被調用的函數                    指針。 這個函數的原型應該為:                    void  on_Mouse( int  event,  int  x,  int  y,  int  flags,  void * param);  userdate:傳給回調函數的參數

MouseCallback onMouse 滑鼠回調函數,響應滑鼠消息(如滑鼠移動,滑鼠左鍵按下,左鍵擡起等)。

函數原型: void on_Mouse(int event, int x, int y, int flags, void* param);

函數參數說明: event:CV_EVENT_*變量之一 x,y:滑鼠指針在圖像坐标系的坐标(不是視窗坐标系)  flags:CV_EVENT_FLAG的組合 param:使用者定義的傳遞到setMouseCallback函數調用的參數。

常用的event:

#defineCV_EVENT_MOUSEMOVE

#defineCV_EVENT_LBUTTONDOWN 

#defineCV_EVENT_RBUTTONDOWN   

#defineCV_EVENT_LBUTTONUP    

#defineCV_EVENT_RBUTTONUP   

和标志位flags有關的:

#defineCV_EVENT_FLAG_LBUTTON 

注意: flags & CV_EVENT_FLAG_LBUTTON 的意思是 提取flags的CV_EVENT_FLAG_LBUTTON 标志位,!()的意思是 标志位無效 例如 if (event == EVENT_MOUSEMOVE && (flags&EVENT_FLAG_LBUTTON))  ,表示滑鼠移動且左鍵按下

grabCut

OpenCV中grabcut函數基于《"GrabCut" - Interactive Foreground Extraction using Iterated Graph Cuts》這篇文章來實作的。該算法利用了圖像中的紋理(顔色)資訊和邊界(反差)資訊,隻要少量的使用者互動操作即可得到比較好的分割結果。如果前景和背景之間的顔色反差不大,分割的效果不好;不過,這種情況下允許手工标記一些前景或背景區域,這樣能得到較好的結果。

以上關于 grabcut算法背景介紹摘抄至參考資料2.《學習OpenCV——學習grabcut算法》

函數原型: void cv::grabCut( const Mat& img, Mat& mask, Rect rect,

             Mat& bgdModel, Mat& fgdModel,

             int iterCount, int mode )

函數參數說明: img:待分割的源圖像,必須是8位3通道(CV_8UC3)圖像,在處理的過程中不會被修改;

mask:掩碼圖像,如果使用掩碼進行初始化,那麼mask儲存初始化掩碼資訊;在執行分割             的時候,也可以将使用者互動所設定的前景與背景儲存到mask中,然後再傳入grabCu             t函數;在處理結束之後,mask中會儲存結果。mask隻能取以下四種值:

            GCD_BGD(=0),背景;

            GCD_FGD(=1),前景;

            GCD_PR_BGD(=2),可能的背景;

            GCD_PR_FGD(=3),可能的前景。

            如果沒有手工标記GCD_BGD或者GCD_FGD,那麼結果隻會有GCD_PR_BGD或GCD_             PR_FGD;

rect:用于限定需要進行分割的圖像範圍,隻有該矩形視窗内的圖像部分才被處理;

bgdModel:背景模型,如果為null,函數内部會自動建立一個bgdModel;bgdModel必                      須是單通道浮點型(CV_32FC1)圖像,且行數隻能為1,列數隻能為13x5;

fgdModel:前景模型,如果為null,函數内部會自動建立一個fgdModel;fgdModel必須                     是單通道浮點型(CV_32FC1)圖像,且行數隻能為1,列數隻能為13x5;

iterCount:疊代次數,必須大于0;

mode:用于訓示grabCut函數進行什麼操作,可選的值有:

             GC_INIT_WITH_RECT(=0),用矩形窗初始化GrabCut;

             GC_INIT_WITH_MASK(=1),用掩碼圖像初始化GrabCut;

             GC_EVAL(=2),執行分割。

Example截圖

OpenCV3.0 Examples學習筆記(10)-grabcut.cpp-grabcut函數實作人機互動高效分割圖像前景背景
OpenCV3.0 Examples學習筆記(10)-grabcut.cpp-grabcut函數實作人機互動高效分割圖像前景背景
OpenCV3.0 Examples學習筆記(10)-grabcut.cpp-grabcut函數實作人機互動高效分割圖像前景背景

Example分析 1.主函數 1.1從指令行參數加載圖像 if( argc!=2 )     {         help();         return 1;     }     string filename = argv[1];     if( filename.empty() )     {         cout << "\nDurn, couldn't read in " << argv[1] << endl;         return 1;     }     Mat image = imread( filename, 1 );     if( image.empty() )     {         cout << "\n Durn, couldn't read image filename " << filename << endl;         return 1;     }

1.2建立預覽視窗 const string winName = "image";     //namedWindow( winName, WINDOW_AUTOSIZE );     namedWindow( winName, WINDOW_NORMAL );

注意: (1)這一次的預覽視窗還支援使用滑鼠繪圖。

1.3設定滑鼠回調 setMouseCallback( winName, on_mouse, 0 );

1.4為 GCApplication對象gcapp設定參數 gcapp.setImageAndWinName( image, winName ); gcapp.showImage();

注意: (1)實際上示例中幾乎所有grabcut極其相關的人機互動操作(滑鼠/鍵盤)都是在 GCApplication類完成。

1.5通過鍵盤錄入修改參數 for(;;)     {         int c = waitKey(0);         switch( (char) c )         {         case '\x1b':             cout << "Exiting ..." << endl;             goto exit_main;         case 'r':             cout << endl;             gcapp.reset();             gcapp.showImage();             break;         case 'n':             int iterCount = gcapp.getIterCount();             cout << "<" << iterCount << "... ";             int newIterCount = gcapp.nextIter();             if( newIterCount > iterCount )             {                 gcapp.showImage();                 cout << iterCount << ">" << endl;             }             else                 cout << "rect must be determined>" << endl;             break;         }     }

注意: (1)Esc: 退出 (2)r:傳回原圖 (3)n:根據設定調用grabcut

1.6釋放視窗 destroyWindow( winName );

2.具體分析示例最重要的GCApplication 2.1初始化所有參數至調用grabcut前 reset

2.2設定圖像和預覽視窗 setImageAndWinName

2.2顯示預覽圖 showImage

2.3滑鼠響應事件,用于人機互動設定grabcut,rect位置 mouseClick

2.4調用grabcut nextIter

2.5傳回處理次數 getIterCount

Example代碼

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

#include <iostream>

using namespace std;
using namespace cv;

static void help()
{
    cout << "\nThis program demonstrates GrabCut segmentation -- select an object in a region\n"
            "and then grabcut will attempt to segment it out.\n"
            "Call:\n"
            "./grabcut <image_name>\n"
        "\nSelect a rectangular area around the object you want to segment\n" <<
        "\nHot keys: \n"
        "\tESC - quit the program\n"
        "\tr - restore the original image\n"
        "\tn - next iteration\n"
        "\n"
        "\tleft mouse button - set rectangle\n"
        "\n"
        "\tCTRL+left mouse button - set GC_BGD pixels\n"
        "\tSHIFT+left mouse button - set GC_FGD pixels\n"
        "\n"
        "\tCTRL+right mouse button - set GC_PR_BGD pixels\n"
        "\tSHIFT+right mouse button - set GC_PR_FGD pixels\n" << endl;
}

const Scalar RED = Scalar(0,0,255);
const Scalar PINK = Scalar(230,130,255);
const Scalar BLUE = Scalar(255,0,0);
const Scalar LIGHTBLUE = Scalar(255,255,160);
const Scalar GREEN = Scalar(0,255,0);

const int BGD_KEY = EVENT_FLAG_CTRLKEY;
const int FGD_KEY = EVENT_FLAG_SHIFTKEY;

static void getBinMask( const Mat& comMask, Mat& binMask )
{
    if( comMask.empty() || comMask.type()!=CV_8UC1 )
        CV_Error( Error::StsBadArg, "comMask is empty or has incorrect type (not CV_8UC1)" );
    if( binMask.empty() || binMask.rows!=comMask.rows || binMask.cols!=comMask.cols )
        binMask.create( comMask.size(), CV_8UC1 );
    binMask = comMask & 1;
}

class GCApplication
{
public:
    enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 };
    static const int radius = 2;
    static const int thickness = -1;

    void reset();
    void setImageAndWinName( const Mat& _image, const string& _winName );
    void showImage() const;
    void mouseClick( int event, int x, int y, int flags, void* param );
    int nextIter();
    int getIterCount() const { return iterCount; }
private:
    void setRectInMask();
    void setLblsInMask( int flags, Point p, bool isPr );

    const string* winName;
    const Mat* image;
    Mat mask;
    Mat bgdModel, fgdModel;

    uchar rectState, lblsState, prLblsState;
    bool isInitialized;

    Rect rect;
    vector<Point> fgdPxls, bgdPxls, prFgdPxls, prBgdPxls;
    int iterCount;
};

void GCApplication::reset()
{
    if( !mask.empty() )
        mask.setTo(Scalar::all(GC_BGD));
    bgdPxls.clear(); fgdPxls.clear();
    prBgdPxls.clear();  prFgdPxls.clear();

    isInitialized = false;
    rectState = NOT_SET;
    lblsState = NOT_SET;
    prLblsState = NOT_SET;
    iterCount = 0;
}

void GCApplication::setImageAndWinName( const Mat& _image, const string& _winName  )
{
    if( _image.empty() || _winName.empty() )
        return;
    image = &_image;
    winName = &_winName;
    mask.create( image->size(), CV_8UC1);
    reset();
}

void GCApplication::showImage() const
{
    if( image->empty() || winName->empty() )
        return;

    Mat res;
    Mat binMask;
    if( !isInitialized )
        image->copyTo( res );
    else
    {
        getBinMask( mask, binMask );
        image->copyTo( res, binMask );
    }

    vector<Point>::const_iterator it;
    for( it = bgdPxls.begin(); it != bgdPxls.end(); ++it )
        circle( res, *it, radius, BLUE, thickness );
    for( it = fgdPxls.begin(); it != fgdPxls.end(); ++it )
        circle( res, *it, radius, RED, thickness );
    for( it = prBgdPxls.begin(); it != prBgdPxls.end(); ++it )
        circle( res, *it, radius, LIGHTBLUE, thickness );
    for( it = prFgdPxls.begin(); it != prFgdPxls.end(); ++it )
        circle( res, *it, radius, PINK, thickness );

    if( rectState == IN_PROCESS || rectState == SET )
        rectangle( res, Point( rect.x, rect.y ), Point(rect.x + rect.width, rect.y + rect.height ), GREEN, 2);

    imshow( *winName, res );
}

void GCApplication::setRectInMask()
{
    CV_Assert( !mask.empty() );
    mask.setTo( GC_BGD );
    rect.x = max(0, rect.x);
    rect.y = max(0, rect.y);
    rect.width = min(rect.width, image->cols-rect.x);
    rect.height = min(rect.height, image->rows-rect.y);
    (mask(rect)).setTo( Scalar(GC_PR_FGD) );
}

void GCApplication::setLblsInMask( int flags, Point p, bool isPr )
{
    vector<Point> *bpxls, *fpxls;
    uchar bvalue, fvalue;
    if( !isPr )
    {
        bpxls = &bgdPxls;
        fpxls = &fgdPxls;
        bvalue = GC_BGD;
        fvalue = GC_FGD;
    }
    else
    {
        bpxls = &prBgdPxls;
        fpxls = &prFgdPxls;
        bvalue = GC_PR_BGD;
        fvalue = GC_PR_FGD;
    }
    if( flags & BGD_KEY )
    {
        bpxls->push_back(p);
        circle( mask, p, radius, bvalue, thickness );
    }
    if( flags & FGD_KEY )
    {
        fpxls->push_back(p);
        circle( mask, p, radius, fvalue, thickness );
    }
}

void GCApplication::mouseClick( int event, int x, int y, int flags, void* )
{
    // TODO add bad args check
    switch( event )
    {
    case EVENT_LBUTTONDOWN: // set rect or GC_BGD(GC_FGD) labels
        {
            bool isb = (flags & BGD_KEY) != 0,
                 isf = (flags & FGD_KEY) != 0;
            if( rectState == NOT_SET && !isb && !isf )
            {
                rectState = IN_PROCESS;
                rect = Rect( x, y, 1, 1 );
            }
            if ( (isb || isf) && rectState == SET )
                lblsState = IN_PROCESS;
        }
        break;
    case EVENT_RBUTTONDOWN: // set GC_PR_BGD(GC_PR_FGD) labels
        {
            bool isb = (flags & BGD_KEY) != 0,
                 isf = (flags & FGD_KEY) != 0;
            if ( (isb || isf) && rectState == SET )
                prLblsState = IN_PROCESS;
        }
        break;
    case EVENT_LBUTTONUP:
        if( rectState == IN_PROCESS )
        {
            rect = Rect( Point(rect.x, rect.y), Point(x,y) );
            rectState = SET;
            setRectInMask();
            CV_Assert( bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty() );
            showImage();
        }
        if( lblsState == IN_PROCESS )
        {
            setLblsInMask(flags, Point(x,y), false);
            lblsState = SET;
            showImage();
        }
        break;
    case EVENT_RBUTTONUP:
        if( prLblsState == IN_PROCESS )
        {
            setLblsInMask(flags, Point(x,y), true);
            prLblsState = SET;
            showImage();
        }
        break;
    case EVENT_MOUSEMOVE:
        if( rectState == IN_PROCESS )
        {
            rect = Rect( Point(rect.x, rect.y), Point(x,y) );
            CV_Assert( bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty() );
            showImage();
        }
        else if( lblsState == IN_PROCESS )
        {
            setLblsInMask(flags, Point(x,y), false);
            showImage();
        }
        else if( prLblsState == IN_PROCESS )
        {
            setLblsInMask(flags, Point(x,y), true);
            showImage();
        }
        break;
    }
}

int GCApplication::nextIter()
{
    if( isInitialized )
        grabCut( *image, mask, rect, bgdModel, fgdModel, 1 );
    else
    {
        if( rectState != SET )
            return iterCount;

        if( lblsState == SET || prLblsState == SET )
            grabCut( *image, mask, rect, bgdModel, fgdModel, 1, GC_INIT_WITH_MASK );
        else
            grabCut( *image, mask, rect, bgdModel, fgdModel, 1, GC_INIT_WITH_RECT );

        isInitialized = true;
    }
    iterCount++;

    bgdPxls.clear(); fgdPxls.clear();
    prBgdPxls.clear(); prFgdPxls.clear();

    return iterCount;
}

GCApplication gcapp;

static void on_mouse( int event, int x, int y, int flags, void* param )
{
    gcapp.mouseClick( event, x, y, flags, param );
}

int main( int argc, char** argv )
{
    if( argc!=2 )
    {
        help();
        return 1;
    }
    string filename = argv[1];
    if( filename.empty() )
    {
        cout << "\nDurn, couldn't read in " << argv[1] << endl;
        return 1;
    }
    Mat image = imread( filename, 1 );
    if( image.empty() )
    {
        cout << "\n Durn, couldn't read image filename " << filename << endl;
        return 1;
    }

    help();

    const string winName = "image";
    namedWindow( winName, WINDOW_AUTOSIZE );
    setMouseCallback( winName, on_mouse, 0 );

    gcapp.setImageAndWinName( image, winName );
    gcapp.showImage();

    for(;;)
    {
        int c = waitKey(0);
        switch( (char) c )
        {
        case '\x1b':
            cout << "Exiting ..." << endl;
            goto exit_main;
        case 'r':
            cout << endl;
            gcapp.reset();
            gcapp.showImage();
            break;
        case 'n':
            int iterCount = gcapp.getIterCount();
            cout << "<" << iterCount << "... ";
            int newIterCount = gcapp.nextIter();
            if( newIterCount > iterCount )
            {
                gcapp.showImage();
                cout << iterCount << ">" << endl;
            }
            else
                cout << "rect must be determined>" << endl;
            break;
        }
    }

exit_main:
    destroyWindow( winName );
    return 0;
}
           

參考資料: 1.《 【OpenCV】 GrabCut.cpp詳解》 2.《 學習OpenCV——學習grabcut算法 》 3.《 Opencv之滑鼠響應setMouseCallback()的用法 》