图像分割——交互式GrabCut算法(c++)纯代码

#include "opencv2/highgui/highgui.hpp"                                                                                               
#include "opencv2/imgproc/imgproc.hpp"
 
#include <iostream>
 
using namespace std;
using namespace cv;
 
string filename;
Mat image;
string winName = "show";
enum{NOT_SET = 0, IN_PROCESS = 1, SET = 2};
uchar rectState;
Rect rect;
Mat mask;
const Scalar GREEN = Scalar(0,255,0);
Mat bgdModel, fgdModel;
 
void setRectInMask(){
    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);
 
}
 
static void getBinMask( const Mat& comMask, Mat& binMask ){
    binMask.create( comMask.size(), CV_8UC1 );
    binMask = comMask & 1;
}
 
void on_mouse( int event, int x, int y, int flags, void* )
{
    Mat res;
    Mat binMask;
 
    switch( event ){
        case CV_EVENT_LBUTTONDOWN:
            if( rectState == NOT_SET){
                rectState = IN_PROCESS;
                rect = Rect( x, y, 1, 1 );
            }
            break;
        case CV_EVENT_LBUTTONUP:
            if( rectState == IN_PROCESS ){
                rect = Rect( Point(rect.x, rect.y), Point(x,y) );
                rectState = SET;
                (mask(rect)).setTo( Scalar(GC_PR_FGD));
                image = imread( filename, 1 );
                grabCut(image, mask, rect, bgdModel, fgdModel, 1, GC_INIT_WITH_RECT);
                getBinMask( mask, binMask );
                image.copyTo(res, binMask );
                imshow("11", res);
            }
            break;
        case CV_EVENT_MOUSEMOVE:
            if( rectState == IN_PROCESS ){
                rect = Rect( Point(rect.x, rect.y), Point(x,y) );
                image = imread( filename, 1 );
                rectangle(image, Point( rect.x, rect.y ), Point(rect.x + rect.width, rect.y + rect.height ), GREEN, 2);
                imshow(winName, image);
            }
            break;
    }
}
 
int main(int argc, char* argv[]){
    filename = "cup.jpg";
    image = imread( filename, 1 );
    imshow(winName, image);
    mask.create(image.size(), CV_8UC1);
    rectState = NOT_SET;
    mask.setTo(GC_BGD);
 
    setMouseCallback(winName, on_mouse, 0);
    waitKey(0);
 
    return 0;
}

 

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值