opencv2 学习第8天 提取分离前景和背景
http://blog.csdn.net/zhouzhouzf/article/details/9281327
GrabCut
代码来自于http://www.cnblogs.com/tornadomeet/archive/2012/11/09/2763271.html
- #include <opencv2/highgui/highgui.hpp>
- #include <opencv2/core/core.hpp>
- #include <vector>
- #include <iostream>
- #include <opencv2/imgproc/imgproc.hpp>
- //#include "../../../../../Downloads/colourhistogram.h"
- 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 CG_FGD pixels\n"
- "\n"
- "\tCTRL+right mouse button - set GC_PR_BGD pixels\n"
- "\tSHIFT+right mouse button - set CG_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 = CV_EVENT_FLAG_CTRLKEY; //Ctrl键
- const int FGD_KEY = CV_EVENT_FLAG_SHIFTKEY; //Shift键
- static void getBinMask( const Mat& comMask, Mat& binMask )
- {
- if( comMask.empty() || comMask.type()!=CV_8UC1 )
- CV_Error( CV_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; //得到mask的最低位,实际上是只保留确定的或者有可能的前景点当做mask
- }
- 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; //NOT_SET == 0
- 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();
- }
- /*显示4个点,一个矩形和图像内容,因为后面的步骤很多地方都要用到这个函数,所以单独拿出来*/
- 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 ); //按照最低位是0还是1来复制,只保留跟前景有关的图像,比如说可能的前景,可能的背景
- }
- vector<Point>::const_iterator it;
- /*下面4句代码是将选中的4个点用不同的颜色显示出来*/
- 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 );
- }
- /*该步骤完成后,mask图像中rect内部是3,外面全是0*/
- void GCApplication::setRectInMask()
- {
- assert( !mask.empty() );
- mask.setTo( GC_BGD ); //GC_BGD == 0
- 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) ); //GC_PR_FGD == 3,矩形内部,为可能的前景点
- }
- 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; //0
- fvalue = GC_FGD; //1
- }
- else //概率点
- {
- bpxls = &prBgdPxls;
- fpxls = &prFgdPxls;
- bvalue = GC_PR_BGD; //2
- fvalue = GC_PR_FGD; //3
- }
- if( flags & BGD_KEY )
- {
- bpxls->push_back(p);
- circle( mask, p, radius, bvalue, thickness ); //该点处为2
- }
- if( flags & FGD_KEY )
- {
- fpxls->push_back(p);
- circle( mask, p, radius, fvalue, thickness ); //该点处为3
- }
- }
- /*鼠标响应函数,参数flags为CV_EVENT_FLAG的组合*/
- void GCApplication::mouseClick( int event, int x, int y, int flags, void* )
- {
- // TODO add bad args check
- switch( event )
- {
- case CV_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 ) //按下了alt键或者shift键,且画好了矩形,表示正在画前景背景点
- lblsState = IN_PROCESS;
- }
- break;
- case CV_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 CV_EVENT_LBUTTONUP:
- if( rectState == IN_PROCESS )
- {
- rect = Rect( Point(rect.x, rect.y), Point(x,y) ); //矩形结束
- rectState = SET;
- setRectInMask();
- 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 CV_EVENT_RBUTTONUP:
- if( prLblsState == IN_PROCESS )
- {
- setLblsInMask(flags, Point(x,y), true); //画出背景点
- prLblsState = SET;
- showImage();
- }
- break;
- case CV_EVENT_MOUSEMOVE:
- if( rectState == IN_PROCESS )
- {
- rect = Rect( Point(rect.x, rect.y), Point(x,y) );
- 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;
- }
- }
- /*该函数进行grabcut算法,并且返回算法运行迭代的次数*/
- int GCApplication::nextIter()
- {
- if( isInitialized )
- //使用grab算法进行一次迭代,参数2为mask,里面存的mask位是:矩形内部除掉那些可能是背景或者已经确定是背景后的所有的点,且mask同时也为输出
- //保存的是分割后的前景图像
- 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 )
- {
- string filename = "D:\\images\\dog.jpg";
- 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";
- cvNamedWindow( winName.c_str(), CV_WINDOW_AUTOSIZE );
- cvSetMouseCallback( winName.c_str(), on_mouse, 0 );
- gcapp.setImageAndWinName( image, winName );
- gcapp.showImage();
- for(;;)
- {
- int c = cvWaitKey(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:
- cvDestroyWindow( winName.c_str() );
- return 0;
- }
opencv2 书本上给的GrabCut的方法代码,实现起来速度也是不太能够忍受
- class WatershedSegmenter {
- private:
- cv::Mat markers;
- public:
- void setMarkers(const cv::Mat& markerImage) {
- // Convert to image of ints
- markerImage.convertTo(markers,CV_32S);
- }
- cv::Mat process(const cv::Mat &image) {
- // Apply watershed
- cv::watershed(image,markers);
- return markers;
- }
- // Return result in the form of an image
- cv::Mat getSegmentation() {
- cv::Mat tmp;
- // all segment with label higher than 255
- // will be assigned value 255
- markers.convertTo(tmp,CV_8U);
- return tmp;
- }
- // Return watershed in the form of an image
- cv::Mat getWatersheds() {
- cv::Mat tmp;
- markers.convertTo(tmp,CV_8U,255,255);
- return tmp;
- }
- };
- int main()
- {
- using namespace cv;
- // Open another image
- Mat image= cv::imread("D:\\images\\tower.jpg");
- // define bounding rectangle
- cv::Rect rectangle(50,70,image.cols-150,image.rows-180);
- 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
- // 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));
- image.copyTo(foreground,result); // bg pixels not copied
- // draw rectangle on original image
- cv::rectangle(image, rectangle, cv::Scalar(255,255,255),1);
- cv::namedWindow("Image");
- cv::imshow("Image",image);
- // display result
- cv::namedWindow("Segmented Image");
- cv::imshow("Segmented Image",foreground);
- // Open another image
- image= cv::imread("D:\\images\\tower.jpg");
- // define bounding rectangle
- cv::Rect rectangle2(10,100,380,180);
- cv::Mat bkgModel,fgrModel; // the models (internally used)
- // GrabCut segmentation
- cv::grabCut(image, // input image
- result, // segmentation result
- rectangle2,bkgModel,fgrModel,5,cv::GC_INIT_WITH_RECT);
- // Get the pixels marked as likely foreground
- // cv::compare(result,cv::GC_PR_FGD,result,cv::CMP_EQ);
- result= result&1;
- foreground.create(image.size(),CV_8UC3);
- foreground.setTo(cv::Scalar(255,255,255));
- image.copyTo(foreground,result); // bg pixels not copied
- // draw rectangle on original image
- cv::rectangle(image, rectangle2, cv::Scalar(255,255,255),1);
- cv::namedWindow("Image 2");
- cv::imshow("Image 2",image);
- // display result
- cv::namedWindow("Foreground objects");
- cv::imshow("Foreground objects",foreground);
- waitKey(0);
- system("pause");
- return 0;
- }
- 顶
- 0
- 踩
opencv2 学习第8天 提取分离前景和背景的更多相关文章
- OpenCV2学习笔记(十四):基于OpenCV卡通图片处理
得知OpenCV有一段时间.除了研究的各种算法的内容.除了从备用,据导游书籍和资料,尝试结合链接的图像处理算法和日常生活,第一桌面上(随着摄像头)完成了一系列的视频流处理功能.开发平台Qt5.3.2+ ...
- 【视频编解码·学习笔记】11. 提取SPS信息程序
一.准备工作: 回到之前SimpleH264Analyzer程序,找到SPS信息,并对其做解析 调整项目目录结构: 修改Global.h文件中代码,添加新数据类型UINT16,之前编写的工程中,UIN ...
- 学习笔记CB002:词干提取、词性标注、中文切词、文档分类
英文词干提取器,import nltk,porter = nltk.PorterStemmer(),porter.stem('lying') . 词性标注器,pos_tag处理词序列,根据句子动态判断 ...
- Python学习笔记五(读取提取写入文件)
#Python打开读取一个文件内容,然后写入一个新的文件中,并对某些字段进行提取,写入新的字段的脚本,与大家共同学习. import os import re def get_filelist(dir ...
- 学习 Antd Pro 前后端分离
1.前言 最近学习reactjs ,前些年用RN开发过移动端,入门还算轻松.现在打算使用 Antd Pro 实现前后端分离.要使用Antd Pro这个脚手架,必须熟悉 umi.dva.redux-sa ...
- 深度学习面试题25:分离卷积(separable卷积)
目录 举例 单个张量与多个卷积核的分离卷积 参考资料 举例 分离卷积就是先在深度上分别卷积,然后再进行卷积,对应代码为: import tensorflow as tf # [batch, in_he ...
- webpack学习之—— Code Spliting(代码分离)
代码分离特性能够把代码分离到不同的 bundle 中,然后可以按需加载或并行加载这些文件.代码分离可以用于获取更小的 bundle,以及控制资源加载优先级,如果使用合理,会极大影响加载时间. 有三种常 ...
- OpenCV2学习笔记(一)
Mat - 图像的容器 在对图像进行处理时,首先需要将图像载入到内存中,而Mat就是图像在内存中的容器,管理着图像在内存中的数据.Mat是C++ 的一个类,由于OpenCV2中引入了内存自动管理机制, ...
- opencv2学习:计算协方差矩阵
图像的高级处理中,协方差矩阵计算是必不可少的,但opencv关于这方面的资料却相当少. 首先,利用matlab计算一下,便于比较: >> data=[1,2,3;10,20,30] dat ...
随机推荐
- vue的递归组件以及三级菜单的制作
js里面有递归算法,同时,我们也可以利用props来实现vue模板的递归调用,但是前提是组件拥有 name 属性 父组件:slotDemo.vue: <template> <div& ...
- nmon工具
下载地址 1.http://nmon.sourceforge.net/pmwiki.php?n=Site.Download tar xvzf *.tar.gz,需要配置权限 chmod -x,同时配 ...
- ios 如何对UITableView中的内容进行排序
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSI ...
- vue 阻止表单默认的提交事件
form <form autocomplete="off" @submit.prevent="onSubmit"> <input type=& ...
- Vue基础-双向绑定:从 html 到 模板 到 渲染函数
Vue 测试版本:Vue.js v2.5.13 在 Vue 中,可以利用 v-model 语法糖实现数据的双向绑定,例如: <div id="app"> <inp ...
- ubuntu squid 代理服务器安装配置
安装: 下载安装包 http://pan.baidu.com/s/1mitvwpE 解压 tar -xzvf file.tar.gz 编译: 进入sbin目录 执行 ./configure --pr ...
- Morphia - mongodb之ORM框架
一.简介 二.注解 1.@Entity 2.@Id3.@Indexed4.@Embedded5.@Transient和@Property6.@Reference 三.示例 四.参考资料 Morphia ...
- Static Import Constant interface
Static Import https://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html In order t ...
- 可能引起「We Were Unable to Load Disqus」错误的一种情况分析
今天想往Octopress里加评论,之前看了网上的教程,应该是简单的事情,因为Octopress本来为你准备好了评论插件Disqus的代码,只需要去Disqus注册个帐号,然后在_config.yml ...
- 1. testNG+Maven 环境搭建
一:使用的工具 : TestNG 6.9.10 Maven 3.5 IDEA 二:创建maven项目,在pom.xml添加依赖 <?xml version="1.0" enc ...