图像分割之(四)OpenCV的GrabCut函数使用和源码解读

来源:互联网 发布:av淘宝看不了了,怎么办 编辑:程序博客网 时间:2024/05/22 10:43


图像分割之(四)OpenCV的GrabCut函数使用和源码解读

zouxy09@qq.com

http://blog.csdn.net/zouxy09

上一文对GrabCut做了一个了解。OpenCV中的GrabCut算法是依据《"GrabCut" - Interactive Foreground Extraction using Iterated Graph Cuts》这篇文章来实现的。现在我对源码做了些注释,以便我们更深入的了解该算法。一直觉得论文和代码是有比较大的差别的,个人觉得脱离代码看论文,最多能看懂70%,剩下20%或者更多就需要通过阅读代码来获得了,那还有10%就和每个人的基础和知识储备相挂钩了。

接触时间有限,若有错误,还望各位前辈指正,谢谢。原论文的一些浅解见上一博文:

http://blog.csdn.net/zouxy09/article/details/8534954

一、GrabCut函数使用

OpenCV的源码目录的samples的文件夹下,有grabCut的使用例程,请参考:

opencv\samples\cpp\grabcut.cpp

grabCut函数的API说明如下:

void cv::grabCut( InputArray _img, InputOutputArray _mask, Rect rect,

InputOutputArray _bgdModel, InputOutputArray _fgdModel,

int iterCount, int mode )

/*

****参数说明:

img——待分割的源图像,必须是83通道(CV_8UC3)图像,在处理的过程中不会被修改;

mask——掩码图像,如果使用掩码进行初始化,那么mask保存初始化掩码信息;在执行分割的时候,也可以将用户交互所设定的前景与背景保存到mask中,然后再传入grabCut函数;在处理结束之后,mask中会保存结果。mask只能取以下四种值:

GCD_BGD=0),背景;

GCD_FGD=1),前景;

GCD_PR_BGD=2),可能的背景;

GCD_PR_FGD=3),可能的前景。

如果没有手工标记GCD_BGD或者GCD_FGD,那么结果只会有GCD_PR_BGDGCD_PR_FGD

rect——用于限定需要进行分割的图像范围,只有该矩形窗口内的图像部分才被处理;

bgdModel——背景模型,如果为null,函数内部会自动创建一个bgdModelbgdModel必须是单通道浮点型(CV_32FC1)图像,且行数只能为1,列数只能为13x5

fgdModel——前景模型,如果为null,函数内部会自动创建一个fgdModelfgdModel必须是单通道浮点型(CV_32FC1)图像,且行数只能为1,列数只能为13x5

iterCount——迭代次数,必须大于0

mode——用于指示grabCut函数进行什么操作,可选的值有:

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

GC_INIT_WITH_MASK=1),用掩码图像初始化GrabCut

GC_EVAL=2),执行分割。

*/

二、GrabCut源码解读

其中源码包含了gcgraph.hpp这个构建图和max flow/min cut算法的实现文件,这个文件暂时没有解读,后面再更新了。

[cpp] view plaincopyprint?
  1. /*M///////////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
  4. //
  5. // By downloading, copying, installing or using the software you agree to this license.
  6. // If you do not agree to this license, do not download, install,
  7. // copy or use the software.
  8. //
  9. //
  10. // Intel License Agreement
  11. // For Open Source Computer Vision Library
  12. //
  13. // Copyright (C) 2000, Intel Corporation, all rights reserved.
  14. // Third party copyrights are property of their respective owners.
  15. //
  16. // Redistribution and use in source and binary forms, with or without modification,
  17. // are permitted provided that the following conditions are met:
  18. //
  19. // * Redistribution's of source code must retain the above copyright notice,
  20. // this list of conditions and the following disclaimer.
  21. //
  22. // * Redistribution's in binary form must reproduce the above copyright notice,
  23. // this list of conditions and the following disclaimer in the documentation
  24. // and/or other materials provided with the distribution.
  25. //
  26. // * The name of Intel Corporation may not be used to endorse or promote products
  27. // derived from this software without specific prior written permission.
  28. //
  29. // This software is provided by the copyright holders and contributors "as is" and
  30. // any express or implied warranties, including, but not limited to, the implied
  31. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  32. // In no event shall the Intel Corporation or contributors be liable for any direct,
  33. // indirect, incidental, special, exemplary, or consequential damages
  34. // (including, but not limited to, procurement of substitute goods or services;
  35. // loss of use, data, or profits; or business interruption) however caused
  36. // and on any theory of liability, whether in contract, strict liability,
  37. // or tort (including negligence or otherwise) arising in any way out of
  38. // the use of this software, even if advised of the possibility of such damage.
  39. //
  40. //M*/
  41. #include "precomp.hpp"
  42. #include "gcgraph.hpp"
  43. #include <limits>
  44. using namespace cv;
  45. /*
  46. This is implementation of image segmentation algorithm GrabCut described in
  47. "GrabCut — Interactive Foreground Extraction using Iterated Graph Cuts".
  48. Carsten Rother, Vladimir Kolmogorov, Andrew Blake.
  49. */
  50. /*
  51. GMM - Gaussian Mixture Model
  52. */
  53. class GMM
  54. {
  55. public:
  56. static const int componentsCount = 5;
  57. GMM( Mat& _model );
  58. double operator()( const Vec3d color ) const;
  59. double operator()( int ci,const Vec3d color )const;
  60. int whichComponent( const Vec3d color ) const;
  61. void initLearning();
  62. void addSample( int ci,const Vec3d color );
  63. void endLearning();
  64. private:
  65. void calcInverseCovAndDeterm( int ci );
  66. Mat model;
  67. double* coefs;
  68. double* mean;
  69. double* cov;
  70. double inverseCovs[componentsCount][3][3]; //协方差的逆矩阵
  71. double covDeterms[componentsCount];//协方差的行列式
  72. double sums[componentsCount][3];
  73. double prods[componentsCount][3][3];
  74. int sampleCounts[componentsCount];
  75. int totalSampleCount;
  76. };
  77. //背景和前景各有一个对应的GMM(混合高斯模型)
  78. GMM::GMM( Mat& _model )
  79. {
  80. //一个像素的(唯一对应)高斯模型的参数个数或者说一个高斯模型的参数个数
  81. //一个像素RGB三个通道值,故3个均值,3*3个协方差,共用一个权值
  82. const int modelSize = 3/*mean*/ + 9/*covariance*/ + 1/*component weight*/;
  83. if( _model.empty() )
  84. {
  85. //一个GMM共有componentsCount个高斯模型,一个高斯模型有modelSize个模型参数
  86. _model.create( 1, modelSize*componentsCount, CV_64FC1 );
  87. _model.setTo(Scalar(0));
  88. }
  89. else if( (_model.type() != CV_64FC1) || (_model.rows != 1) || (_model.cols != modelSize*componentsCount) )
  90. CV_Error( CV_StsBadArg, "_model must have CV_64FC1 type, rows == 1 and cols == 13*componentsCount" );
  91. model = _model;
  92. //注意这些模型参数的存储方式:先排完componentsCount个coefs,再3*componentsCount个mean。
  93. //再3*3*componentsCount个cov。
  94. coefs = model.ptr<double>(0); //GMM的每个像素的高斯模型的权值变量起始存储指针
  95. mean = coefs + componentsCount; //均值变量起始存储指针
  96. cov = mean + 3*componentsCount; //协方差变量起始存储指针
  97. for( int ci = 0; ci < componentsCount; ci++ )
  98. if( coefs[ci] > 0 )
  99. //计算GMM中第ci个高斯模型的协方差的逆Inverse和行列式Determinant
  100. //为了后面计算每个像素属于该高斯模型的概率(也就是数据能量项)
  101. calcInverseCovAndDeterm( ci );
  102. }
  103. //计算一个像素(由color=(B,G,R)三维double型向量来表示)属于这个GMM混合高斯模型的概率。
  104. //也就是把这个像素像素属于componentsCount个高斯模型的概率与对应的权值相乘再相加,
  105. //具体见论文的公式(10)。结果从res返回。
  106. //这个相当于计算Gibbs能量的第一个能量项(取负后)。
  107. double GMM::operator()( const Vec3d color ) const
  108. {
  109. double res = 0;
  110. for( int ci = 0; ci < componentsCount; ci++ )
  111. res += coefs[ci] * (*this)(ci, color );
  112. return res;
  113. }
  114. //计算一个像素(由color=(B,G,R)三维double型向量来表示)属于第ci个高斯模型的概率。
  115. //具体过程,即高阶的高斯密度模型计算式,具体见论文的公式(10)。结果从res返回
  116. double GMM::operator()( int ci, const Vec3d color ) const
  117. {
  118. double res = 0;
  119. if( coefs[ci] > 0 )
  120. {
  121. CV_Assert( covDeterms[ci] > std::numeric_limits<double>::epsilon() );
  122. Vec3d diff = color;
  123. double* m = mean + 3*ci;
  124. diff[0] -= m[0]; diff[1] -= m[1]; diff[2] -= m[2];
  125. double mult = diff[0]*(diff[0]*inverseCovs[ci][0][0] + diff[1]*inverseCovs[ci][1][0] + diff[2]*inverseCovs[ci][2][0])
  126. + diff[1]*(diff[0]*inverseCovs[ci][0][1] + diff[1]*inverseCovs[ci][1][1] + diff[2]*inverseCovs[ci][2][1])
  127. + diff[2]*(diff[0]*inverseCovs[ci][0][2] + diff[1]*inverseCovs[ci][1][2] + diff[2]*inverseCovs[ci][2][2]);
  128. res = 1.0f/sqrt(covDeterms[ci]) * exp(-0.5f*mult);
  129. }
  130. return res;
  131. }
  132. //返回这个像素最有可能属于GMM中的哪个高斯模型(概率最大的那个)
  133. int GMM::whichComponent( const Vec3d color ) const
  134. {
  135. int k = 0;
  136. double max = 0;
  137. for( int ci = 0; ci < componentsCount; ci++ )
  138. {
  139. double p = (*this)( ci, color );
  140. if( p > max )
  141. {
  142. k = ci; //找到概率最大的那个,或者说计算结果最大的那个
  143. max = p;
  144. }
  145. }
  146. return k;
  147. }
  148. //GMM参数学习前的初始化,主要是对要求和的变量置零
  149. void GMM::initLearning()
  150. {
  151. for( int ci = 0; ci < componentsCount; ci++)
  152. {
  153. sums[ci][0] = sums[ci][1] = sums[ci][2] = 0;
  154. prods[ci][0][0] = prods[ci][0][1] = prods[ci][0][2] = 0;
  155. prods[ci][1][0] = prods[ci][1][1] = prods[ci][1][2] = 0;
  156. prods[ci][2][0] = prods[ci][2][1] = prods[ci][2][2] = 0;
  157. sampleCounts[ci] = 0;
  158. }
  159. totalSampleCount = 0;
  160. }
  161. //增加样本,即为前景或者背景GMM的第ci个高斯模型的像素集(这个像素集是来用估
  162. //计计算这个高斯模型的参数的)增加样本像素。计算加入color这个像素后,像素集
  163. //中所有像素的RGB三个通道的和sums(用来计算均值),还有它的prods(用来计算协方差),
  164. //并且记录这个像素集的像素个数和总的像素个数(用来计算这个高斯模型的权值)。
  165. void GMM::addSample( int ci,const Vec3d color )
  166. {
  167. sums[ci][0] += color[0]; sums[ci][1] += color[1]; sums[ci][2] += color[2];
  168. prods[ci][0][0] += color[0]*color[0]; prods[ci][0][1] += color[0]*color[1]; prods[ci][0][2] += color[0]*color[2];
  169. prods[ci][1][0] += color[1]*color[0]; prods[ci][1][1] += color[1]*color[1]; prods[ci][1][2] += color[1]*color[2];
  170. prods[ci][2][0] += color[2]*color[0]; prods[ci][2][1] += color[2]*color[1]; prods[ci][2][2] += color[2]*color[2];
  171. sampleCounts[ci]++;
  172. totalSampleCount++;
  173. }
  174. //从图像数据中学习GMM的参数:每一个高斯分量的权值、均值和协方差矩阵;
  175. //这里相当于论文中“Iterative minimisation”的step 2
  176. void GMM::endLearning()
  177. {
  178. const double variance = 0.01;
  179. for( int ci = 0; ci < componentsCount; ci++ )
  180. {
  181. int n = sampleCounts[ci]; //第ci个高斯模型的样本像素个数
  182. if( n == 0 )
  183. coefs[ci] = 0;
  184. else
  185. {
  186. //计算第ci个高斯模型的权值系数
  187. coefs[ci] = (double)n/totalSampleCount;
  188. //计算第ci个高斯模型的均值
  189. double* m = mean + 3*ci;
  190. m[0] = sums[ci][0]/n; m[1] = sums[ci][1]/n; m[2] = sums[ci][2]/n;
  191. //计算第ci个高斯模型的协方差
  192. double* c = cov + 9*ci;
  193. c[0] = prods[ci][0][0]/n - m[0]*m[0]; c[1] = prods[ci][0][1]/n - m[0]*m[1]; c[2] = prods[ci][0][2]/n - m[0]*m[2];
  194. c[3] = prods[ci][1][0]/n - m[1]*m[0]; c[4] = prods[ci][1][1]/n - m[1]*m[1]; c[5] = prods[ci][1][2]/n - m[1]*m[2];
  195. c[6] = prods[ci][2][0]/n - m[2]*m[0]; c[7] = prods[ci][2][1]/n - m[2]*m[1]; c[8] = prods[ci][2][2]/n - m[2]*m[2];
  196. //计算第ci个高斯模型的协方差的行列式
  197. double dtrm = c[0]*(c[4]*c[8]-c[5]*c[7]) - c[1]*(c[3]*c[8]-c[5]*c[6]) + c[2]*(c[3]*c[7]-c[4]*c[6]);
  198. if( dtrm <= std::numeric_limits<double>::epsilon() )
  199. {
  200. //相当于如果行列式小于等于0,(对角线元素)增加白噪声,避免其变
  201. //为退化(降秩)协方差矩阵(不存在逆矩阵,但后面的计算需要计算逆矩阵)。
  202. // Adds the white noise to avoid singular covariance matrix.
  203. c[0] += variance;
  204. c[4] += variance;
  205. c[8] += variance;
  206. }
  207. //计算第ci个高斯模型的协方差的逆Inverse和行列式Determinant
  208. calcInverseCovAndDeterm(ci);
  209. }
  210. }
  211. }
  212. //计算协方差的逆Inverse和行列式Determinant
  213. void GMM::calcInverseCovAndDeterm( int ci )
  214. {
  215. if( coefs[ci] > 0 )
  216. {
  217. //取第ci个高斯模型的协方差的起始指针
  218. double *c = cov + 9*ci;
  219. double dtrm =
  220. covDeterms[ci] = c[0]*(c[4]*c[8]-c[5]*c[7]) - c[1]*(c[3]*c[8]-c[5]*c[6])
  221. + c[2]*(c[3]*c[7]-c[4]*c[6]);
  222. //在C++中,每一种内置的数据类型都拥有不同的属性, 使用<limits>库可以获
  223. //得这些基本数据类型的数值属性。因为浮点算法的截断,所以使得,当a=2,
  224. //b=3时 10*a/b == 20/b不成立。那怎么办呢?
  225. //这个小正数(epsilon)常量就来了,小正数通常为可用给定数据类型的
  226. //大于1的最小值与1之差来表示。若dtrm结果不大于小正数,那么它几乎为零。
  227. //所以下式保证dtrm>0,即行列式的计算正确(协方差对称正定,故行列式大于0)。
  228. CV_Assert( dtrm > std::numeric_limits<double>::epsilon() );
  229. //三阶方阵的求逆
  230. inverseCovs[ci][0][0] = (c[4]*c[8] - c[5]*c[7]) / dtrm;
  231. inverseCovs[ci][1][0] = -(c[3]*c[8] - c[5]*c[6]) / dtrm;
  232. inverseCovs[ci][2][0] = (c[3]*c[7] - c[4]*c[6]) / dtrm;
  233. inverseCovs[ci][0][1] = -(c[1]*c[8] - c[2]*c[7]) / dtrm;
  234. inverseCovs[ci][1][1] = (c[0]*c[8] - c[2]*c[6]) / dtrm;
  235. inverseCovs[ci][2][1] = -(c[0]*c[7] - c[1]*c[6]) / dtrm;
  236. inverseCovs[ci][0][2] = (c[1]*c[5] - c[2]*c[4]) / dtrm;
  237. inverseCovs[ci][1][2] = -(c[0]*c[5] - c[2]*c[3]) / dtrm;
  238. inverseCovs[ci][2][2] = (c[0]*c[4] - c[1]*c[3]) / dtrm;
  239. }
  240. }
  241. //计算beta,也就是Gibbs能量项中的第二项(平滑项)中的指数项的beta,用来调整
  242. //高或者低对比度时,两个邻域像素的差别的影响的,例如在低对比度时,两个邻域
  243. //像素的差别可能就会比较小,这时候需要乘以一个较大的beta来放大这个差别,
  244. //在高对比度时,则需要缩小本身就比较大的差别。
  245. //所以我们需要分析整幅图像的对比度来确定参数beta,具体的见论文公式(5)。
  246. /*
  247. Calculate beta - parameter of GrabCut algorithm.
  248. beta = 1/(2*avg(sqr(||color[i] - color[j]||)))
  249. */
  250. static double calcBeta(const Mat& img )
  251. {
  252. double beta = 0;
  253. for( int y = 0; y < img.rows; y++ )
  254. {
  255. for( int x = 0; x < img.cols; x++ )
  256. {
  257. //计算四个方向邻域两像素的差别,也就是欧式距离或者说二阶范数
  258. //(当所有像素都算完后,就相当于计算八邻域的像素差了)
  259. Vec3d color = img.at<Vec3b>(y,x);
  260. if( x>0 ) // left >0的判断是为了避免在图像边界的时候还计算,导致越界
  261. {
  262. Vec3d diff = color - (Vec3d)img.at<Vec3b>(y,x-1);
  263. beta += diff.dot(diff); //矩阵的点乘,也就是各个元素平方的和
  264. }
  265. if( y>0 && x>0 ) // upleft
  266. {
  267. Vec3d diff = color - (Vec3d)img.at<Vec3b>(y-1,x-1);
  268. beta += diff.dot(diff);
  269. }
  270. if( y>0 ) // up
  271. {
  272. Vec3d diff = color - (Vec3d)img.at<Vec3b>(y-1,x);
  273. beta += diff.dot(diff);
  274. }
  275. if( y>0 && x<img.cols-1) // upright
  276. {
  277. Vec3d diff = color - (Vec3d)img.at<Vec3b>(y-1,x+1);
  278. beta += diff.dot(diff);
  279. }
  280. }
  281. }
  282. if( beta <= std::numeric_limits<double>::epsilon() )
  283. beta = 0;
  284. else
  285. beta = 1.f / (2 * beta/(4*img.cols*img.rows - 3*img.cols - 3*img.rows + 2) );//论文公式(5)
  286. return beta;
  287. }
  288. //计算图每个非端点顶点(也就是每个像素作为图的一个顶点,不包括源点s和汇点t)与邻域顶点
  289. //的边的权值。由于是无向图,我们计算的是八邻域,那么对于一个顶点,我们计算四个方向就行,
  290. //在其他的顶点计算的时候,会把剩余那四个方向的权值计算出来。这样整个图算完后,每个顶点
  291. //与八邻域的顶点的边的权值就都计算出来了。
  292. //这个相当于计算Gibbs能量的第二个能量项(平滑项),具体见论文中公式(4)
  293. /*
  294. Calculate weights of noterminal vertices of graph.
  295. beta and gamma - parameters of GrabCut algorithm.
  296. */
  297. static void calcNWeights(const Mat& img, Mat& leftW, Mat& upleftW, Mat& upW,
  298. Mat& uprightW, double beta, double gamma )
  299. {
  300. //gammaDivSqrt2相当于公式(4)中的gamma * dis(i,j)^(-1),那么可以知道,
  301. //当i和j是垂直或者水平关系时,dis(i,j)=1,当是对角关系时,dis(i,j)=sqrt(2.0f)。
  302. //具体计算时,看下面就明白了
  303. const double gammaDivSqrt2 = gamma / std::sqrt(2.0f);
  304. //每个方向的边的权值通过一个和图大小相等的Mat来保存
  305. leftW.create( img.rows, img.cols, CV_64FC1 );
  306. upleftW.create( img.rows, img.cols, CV_64FC1 );
  307. upW.create( img.rows, img.cols, CV_64FC1 );
  308. uprightW.create( img.rows, img.cols, CV_64FC1 );
  309. for( int y = 0; y < img.rows; y++ )
  310. {
  311. for( int x = 0; x < img.cols; x++ )
  312. {
  313. Vec3d color = img.at<Vec3b>(y,x);
  314. if( x-1>=0 ) // left //避免图的边界
  315. {
  316. Vec3d diff = color - (Vec3d)img.at<Vec3b>(y,x-1);
  317. leftW.at<double>(y,x) = gamma * exp(-beta*diff.dot(diff));
  318. }
  319. else
  320. leftW.at<double>(y,x) = 0;
  321. if( x-1>=0 && y-1>=0 ) // upleft
  322. {
  323. Vec3d diff = color - (Vec3d)img.at<Vec3b>(y-1,x-1);
  324. upleftW.at<double>(y,x) = gammaDivSqrt2 * exp(-beta*diff.dot(diff));
  325. }
  326. else
  327. upleftW.at<double>(y,x) = 0;
  328. if( y-1>=0 ) // up
  329. {
  330. Vec3d diff = color - (Vec3d)img.at<Vec3b>(y-1,x);
  331. upW.at<double>(y,x) = gamma * exp(-beta*diff.dot(diff));
  332. }
  333. else
  334. upW.at<double>(y,x) = 0;
  335. if( x+1<img.cols && y-1>=0 ) // upright
  336. {
  337. Vec3d diff = color - (Vec3d)img.at<Vec3b>(y-1,x+1);
  338. uprightW.at<double>(y,x) = gammaDivSqrt2 * exp(-beta*diff.dot(diff));
  339. }
  340. else
  341. uprightW.at<double>(y,x) = 0;
  342. }
  343. }
  344. }
  345. //检查mask的正确性。mask为通过用户交互或者程序设定的,它是和图像大小一样的单通道灰度图,
  346. //每个像素只能取GC_BGD or GC_FGD or GC_PR_BGD or GC_PR_FGD 四种枚举值,分别表示该像素
  347. //(用户或者程序指定)属于背景、前景、可能为背景或者可能为前景像素。具体的参考:
  348. //ICCV2001“Interactive Graph Cuts for Optimal Boundary & Region Segmentation of Objects in N-D Images”
  349. //Yuri Y. Boykov Marie-Pierre Jolly
  350. /*
  351. Check size, type and element values of mask matrix.
  352. */
  353. static void checkMask(const Mat& img,const Mat& mask )
  354. {
  355. if( mask.empty() )
  356. CV_Error( CV_StsBadArg, "mask is empty" );
  357. if( mask.type() != CV_8UC1 )
  358. CV_Error( CV_StsBadArg, "mask must have CV_8UC1 type" );
  359. if( mask.cols != img.cols || mask.rows != img.rows )
  360. CV_Error( CV_StsBadArg, "mask must have as many rows and cols as img" );
  361. for( int y = 0; y < mask.rows; y++ )
  362. {
  363. for( int x = 0; x < mask.cols; x++ )
  364. {
  365. uchar val = mask.at<uchar>(y,x);
  366. if( val!=GC_BGD && val!=GC_FGD && val!=GC_PR_BGD && val!=GC_PR_FGD )
  367. CV_Error( CV_StsBadArg, "mask element value must be equel"
  368. "GC_BGD or GC_FGD or GC_PR_BGD or GC_PR_FGD" );
  369. }
  370. }
  371. }
  372. //通过用户框选目标rect来创建mask,rect外的全部作为背景,设置为GC_BGD,
  373. //rect内的设置为 GC_PR_FGD(可能为前景)
  374. /*
  375. Initialize mask using rectangular.
  376. */
  377. static void initMaskWithRect( Mat& mask, Size imgSize, Rect rect )
  378. {
  379. mask.create( imgSize, CV_8UC1 );
  380. mask.setTo( GC_BGD );
  381. rect.x = max(0, rect.x);
  382. rect.y = max(0, rect.y);
  383. rect.width = min(rect.width, imgSize.width-rect.x);
  384. rect.height = min(rect.height, imgSize.height-rect.y);
  385. (mask(rect)).setTo( Scalar(GC_PR_FGD) );
  386. }
  387. //通过k-means算法来初始化背景GMM和前景GMM模型
  388. /*
  389. Initialize GMM background and foreground models using kmeans algorithm.
  390. */
  391. static void initGMMs(const Mat& img,const Mat& mask, GMM& bgdGMM, GMM& fgdGMM )
  392. {
  393. const int kMeansItCount = 10;//迭代次数
  394. const int kMeansType = KMEANS_PP_CENTERS;//Use kmeans++ center initialization by Arthur and Vassilvitskii
  395. Mat bgdLabels, fgdLabels; //记录背景和前景的像素样本集中每个像素对应GMM的哪个高斯模型,论文中的kn
  396. vector<Vec3f> bgdSamples, fgdSamples; //背景和前景的像素样本集
  397. Point p;
  398. for( p.y = 0; p.y < img.rows; p.y++ )
  399. {
  400. for( p.x = 0; p.x < img.cols; p.x++ )
  401. {
  402. //mask中标记为GC_BGD和GC_PR_BGD的像素都作为背景的样本像素
  403. if( mask.at<uchar>(p) == GC_BGD || mask.at<uchar>(p) == GC_PR_BGD )
  404. bgdSamples.push_back( (Vec3f)img.at<Vec3b>(p) );
  405. else // GC_FGD | GC_PR_FGD
  406. fgdSamples.push_back( (Vec3f)img.at<Vec3b>(p) );
  407. }
  408. }
  409. CV_Assert( !bgdSamples.empty() && !fgdSamples.empty() );
  410. //kmeans中参数_bgdSamples为:每行一个样本
  411. //kmeans的输出为bgdLabels,里面保存的是输入样本集中每一个样本对应的类标签(样本聚为componentsCount类后)
  412. Mat _bgdSamples( (int)bgdSamples.size(), 3, CV_32FC1, &bgdSamples[0][0] );
  413. kmeans( _bgdSamples, GMM::componentsCount, bgdLabels,
  414. TermCriteria( CV_TERMCRIT_ITER, kMeansItCount, 0.0), 0, kMeansType );
  415. Mat _fgdSamples( (int)fgdSamples.size(), 3, CV_32FC1, &fgdSamples[0][0] );
  416. kmeans( _fgdSamples, GMM::componentsCount, fgdLabels,
  417. TermCriteria( CV_TERMCRIT_ITER, kMeansItCount, 0.0), 0, kMeansType );
  418. //经过上面的步骤后,每个像素所属的高斯模型就确定的了,那么就可以估计GMM中每个高斯模型的参数了。
  419. bgdGMM.initLearning();
  420. for( int i = 0; i < (int)bgdSamples.size(); i++ )
  421. bgdGMM.addSample( bgdLabels.at<int>(i,0), bgdSamples[i] );
  422. bgdGMM.endLearning();
  423. fgdGMM.initLearning();
  424. for( int i = 0; i < (int)fgdSamples.size(); i++ )
  425. fgdGMM.addSample( fgdLabels.at<int>(i,0), fgdSamples[i] );
  426. fgdGMM.endLearning();
  427. }
  428. //论文中:迭代最小化算法step 1:为每个像素分配GMM中所属的高斯模型,kn保存在Mat compIdxs中
  429. /*
  430. Assign GMMs components for each pixel.
  431. */
  432. static void assignGMMsComponents(const Mat& img,const Mat& mask,const GMM& bgdGMM,
  433. const GMM& fgdGMM, Mat& compIdxs )
  434. {
  435. Point p;
  436. for( p.y = 0; p.y < img.rows; p.y++ )
  437. {
  438. for( p.x = 0; p.x < img.cols; p.x++ )
  439. {
  440. Vec3d color = img.at<Vec3b>(p);
  441. //通过mask来判断该像素属于背景像素还是前景像素,再判断它属于前景或者背景GMM中的哪个高斯分量
  442. compIdxs.at<int>(p) = mask.at<uchar>(p) == GC_BGD || mask.at<uchar>(p) == GC_PR_BGD ?
  443. bgdGMM.whichComponent(color) : fgdGMM.whichComponent(color);
  444. }
  445. }
  446. }
  447. //论文中:迭代最小化算法step 2:从每个高斯模型的像素样本集中学习每个高斯模型的参数
  448. /*
  449. Learn GMMs parameters.
  450. */
  451. static void learnGMMs(const Mat& img,const Mat& mask,const Mat& compIdxs, GMM& bgdGMM, GMM& fgdGMM )
  452. {
  453. bgdGMM.initLearning();
  454. fgdGMM.initLearning();
  455. Point p;
  456. for( int ci = 0; ci < GMM::componentsCount; ci++ )
  457. {
  458. for( p.y = 0; p.y < img.rows; p.y++ )
  459. {
  460. for( p.x = 0; p.x < img.cols; p.x++ )
  461. {
  462. if( compIdxs.at<int>(p) == ci )
  463. {
  464. if( mask.at<uchar>(p) == GC_BGD || mask.at<uchar>(p) == GC_PR_BGD )
  465. bgdGMM.addSample( ci, img.at<Vec3b>(p) );
  466. else
  467. fgdGMM.addSample( ci, img.at<Vec3b>(p) );
  468. }
  469. }
  470. }
  471. }
  472. bgdGMM.endLearning();
  473. fgdGMM.endLearning();
  474. }
  475. //通过计算得到的能量项构建图,图的顶点为像素点,图的边由两部分构成,
  476. //一类边是:每个顶点与Sink汇点t(代表背景)和源点Source(代表前景)连接的边,
  477. //这类边的权值通过Gibbs能量项的第一项能量项来表示。
  478. //另一类边是:每个顶点与其邻域顶点连接的边,这类边的权值通过Gibbs能量项的第二项能量项来表示。
  479. /*
  480. Construct GCGraph
  481. */
  482. static void constructGCGraph(const Mat& img,const Mat& mask,const GMM& bgdGMM,const GMM& fgdGMM,double lambda,
  483. const Mat& leftW, const Mat& upleftW,const Mat& upW,const Mat& uprightW,
  484. GCGraph<double>& graph )
  485. {
  486. int vtxCount = img.cols*img.rows; //顶点数,每一个像素是一个顶点
  487. int edgeCount = 2*(4*vtxCount - 3*(img.cols + img.rows) + 2);//边数,需要考虑图边界的边的缺失
  488. //通过顶点数和边数创建图。这些类型声明和函数定义请参考gcgraph.hpp
  489. graph.create(vtxCount, edgeCount);
  490. Point p;
  491. for( p.y = 0; p.y < img.rows; p.y++ )
  492. {
  493. for( p.x = 0; p.x < img.cols; p.x++)
  494. {
  495. // add node
  496. int vtxIdx = graph.addVtx(); //返回这个顶点在图中的索引
  497. Vec3b color = img.at<Vec3b>(p);
  498. // set t-weights
  499. //计算每个顶点与Sink汇点t(代表背景)和源点Source(代表前景)连接的权值。
  500. //也即计算Gibbs能量(每一个像素点作为背景像素或者前景像素)的第一个能量项
  501. double fromSource, toSink;
  502. if( mask.at<uchar>(p) == GC_PR_BGD || mask.at<uchar>(p) == GC_PR_FGD )
  503. {
  504. //对每一个像素计算其作为背景像素或者前景像素的第一个能量项,作为分别与t和s点的连接权值
  505. fromSource = -log( bgdGMM(color) );
  506. toSink = -log( fgdGMM(color) );
  507. }
  508. else if( mask.at<uchar>(p) == GC_BGD )
  509. {
  510. //对于确定为背景的像素点,它与Source点(前景)的连接为0,与Sink点的连接为lambda
  511. fromSource = 0;
  512. toSink = lambda;
  513. }
  514. else // GC_FGD
  515. {
  516. fromSource = lambda;
  517. toSink = 0;
  518. }
  519. //设置该顶点vtxIdx分别与Source点和Sink点的连接权值
  520. graph.addTermWeights( vtxIdx, fromSource, toSink );
  521. // set n-weights n-links
  522. //计算两个邻域顶点之间连接的权值。
  523. //也即计算Gibbs能量的第二个能量项(平滑项)
  524. if( p.x>0 )
  525. {
  526. double w = leftW.at<double>(p);
  527. graph.addEdges( vtxIdx, vtxIdx-1, w, w );
  528. }
  529. if( p.x>0 && p.y>0 )
  530. {
  531. double w = upleftW.at<double>(p);
  532. graph.addEdges( vtxIdx, vtxIdx-img.cols-1, w, w );
  533. }
  534. if( p.y>0 )
  535. {
  536. double w = upW.at<double>(p);
  537. graph.addEdges( vtxIdx, vtxIdx-img.cols, w, w );
  538. }
  539. if( p.x<img.cols-1 && p.y>0 )
  540. {
  541. double w = uprightW.at<double>(p);
  542. graph.addEdges( vtxIdx, vtxIdx-img.cols+1, w, w );
  543. }
  544. }
  545. }
  546. }
  547. //论文中:迭代最小化算法step 3:分割估计:最小割或者最大流算法
  548. /*
  549. Estimate segmentation using MaxFlow algorithm
  550. */
  551. static void estimateSegmentation( GCGraph<double>& graph, Mat& mask )
  552. {
  553. //通过最大流算法确定图的最小割,也即完成图像的分割
  554. graph.maxFlow();
  555. Point p;
  556. for( p.y = 0; p.y < mask.rows; p.y++ )
  557. {
  558. for( p.x = 0; p.x < mask.cols; p.x++ )
  559. {
  560. //通过图分割的结果来更新mask,即最后的图像分割结果。注意的是,永远都
  561. //不会更新用户指定为背景或者前景的像素
  562. if( mask.at<uchar>(p) == GC_PR_BGD || mask.at<uchar>(p) == GC_PR_FGD )
  563. {
  564. if( graph.inSourceSegment( p.y*mask.cols+p.x /*vertex index*/ ) )
  565. mask.at<uchar>(p) = GC_PR_FGD;
  566. else
  567. mask.at<uchar>(p) = GC_PR_BGD;
  568. }
  569. }
  570. }
  571. }
  572. //最后的成果:提供给外界使用的伟大的API:grabCut
  573. /*
  574. ****参数说明:
  575. img——待分割的源图像,必须是8位3通道(CV_8UC3)图像,在处理的过程中不会被修改;
  576. mask——掩码图像,如果使用掩码进行初始化,那么mask保存初始化掩码信息;在执行分割
  577. 的时候,也可以将用户交互所设定的前景与背景保存到mask中,然后再传入grabCut函
  578. 数;在处理结束之后,mask中会保存结果。mask只能取以下四种值:
  579. GCD_BGD(=0),背景;
  580. GCD_FGD(=1),前景;
  581. GCD_PR_BGD(=2),可能的背景;
  582. GCD_PR_FGD(=3),可能的前景。
  583. 如果没有手工标记GCD_BGD或者GCD_FGD,那么结果只会有GCD_PR_BGD或GCD_PR_FGD;
  584. rect——用于限定需要进行分割的图像范围,只有该矩形窗口内的图像部分才被处理;
  585. bgdModel——背景模型,如果为null,函数内部会自动创建一个bgdModel;bgdModel必须是
  586. 单通道浮点型(CV_32FC1)图像,且行数只能为1,列数只能为13x5;
  587. fgdModel——前景模型,如果为null,函数内部会自动创建一个fgdModel;fgdModel必须是
  588. 单通道浮点型(CV_32FC1)图像,且行数只能为1,列数只能为13x5;
  589. iterCount——迭代次数,必须大于0;
  590. mode——用于指示grabCut函数进行什么操作,可选的值有:
  591. GC_INIT_WITH_RECT(=0),用矩形窗初始化GrabCut;
  592. GC_INIT_WITH_MASK(=1),用掩码图像初始化GrabCut;
  593. GC_EVAL(=2),执行分割。
  594. */
  595. void cv::grabCut( InputArray _img, InputOutputArray _mask, Rect rect,
  596. InputOutputArray _bgdModel, InputOutputArray _fgdModel,
  597. int iterCount, int mode )
  598. {
  599. Mat img = _img.getMat();
  600. Mat& mask = _mask.getMatRef();
  601. Mat& bgdModel = _bgdModel.getMatRef();
  602. Mat& fgdModel = _fgdModel.getMatRef();
  603. if( img.empty() )
  604. CV_Error( CV_StsBadArg, "image is empty" );
  605. if( img.type() != CV_8UC3 )
  606. CV_Error( CV_StsBadArg, "image mush have CV_8UC3 type" );
  607. GMM bgdGMM( bgdModel ), fgdGMM( fgdModel );
  608. Mat compIdxs( img.size(), CV_32SC1 );
  609. if( mode == GC_INIT_WITH_RECT || mode == GC_INIT_WITH_MASK )
  610. {
  611. if( mode == GC_INIT_WITH_RECT )
  612. initMaskWithRect( mask, img.size(), rect );
  613. else // flag == GC_INIT_WITH_MASK
  614. checkMask( img, mask );
  615. initGMMs( img, mask, bgdGMM, fgdGMM );
  616. }
  617. if( iterCount <= 0)
  618. return;
  619. if( mode == GC_EVAL )
  620. checkMask( img, mask );
  621. const double gamma = 50;
  622. const double lambda = 9*gamma;
  623. const double beta = calcBeta( img );
  624. Mat leftW, upleftW, upW, uprightW;
  625. calcNWeights( img, leftW, upleftW, upW, uprightW, beta, gamma );
  626. for( int i = 0; i < iterCount; i++ )
  627. {
  628. GCGraph<double> graph;
  629. assignGMMsComponents( img, mask, bgdGMM, fgdGMM, compIdxs );
  630. learnGMMs( img, mask, compIdxs, bgdGMM, fgdGMM );
  631. constructGCGraph(img, mask, bgdGMM, fgdGMM, lambda, leftW, upleftW, upW, uprightW, graph );
  632. estimateSegmentation( graph, mask );
  633. }
  634. }