05192017区域生长算法

区域生长实现的步骤如下:
1. 对图像顺序扫描!找到第1个还没有归属的像素, 设该像素为(x0, y0);
2. 以(x0, y0)为中心, 考虑(x0, y0)的8邻域像素(x, y)如果(x0, y0)满足生长准则, 将(x, y)与(x0, y0)合并(在同一区域内), 同时将(x, y)压入堆栈;
3. 从堆栈中取出一个像素, 把它当作(x0, y0)返回到步骤2;
4. 当堆栈为空时!返回到步骤1;
5. 重复步骤1 - 4直到图像中的每个点都有归属时。生长结束。

 

  1. #include <iostream>  
  2. #include <stack>  
  3. #include <opencv2\opencv.hpp>  
  4.   
  5. using namespace std;  
  6. using namespace cv;  
  7.   
  8. // 8 邻域  
  9. static Point connects[8] = { Point(-1, -1), Point(0, -1), Point(1, -1), Point(1, 0), Point(1, 1), Point(0, 1), Point(-1, 1), Point(-1, 0)};  
  10.   
  11. int main()  
  12. {  
  13.     // 原图  
  14.     Mat src = imread("img2.jpg", 0);  
  15.     // 结果图  
  16.     Mat res = Mat::zeros(src.rows, src.cols, CV_8U);  
  17.     // 用于标记是否遍历过某点  
  18.     Mat flagMat;  
  19.     res.copyTo(flagMat);  
  20.     // 二值图像  
  21.     Mat bin;  
  22.     threshold(src, bin, 80, 255, CV_THRESH_BINARY);     // 在此直接将灰度图像二值化,使得后面的区域生长处理失去了意义有木有? 
  23.   
  24.     // 初始3个种子点  
  25.     stack<Point> seeds;  
  26.     seeds.push(Point(0, 0));  
  27.     seeds.push(Point(186, 166));  
  28.     seeds.push(Point(327, 43));  
  29.     res.at<uchar>(0, 0) = 255;  
  30.     res.at<uchar>(166, 186) = 255;  
  31.     res.at<uchar>(43, 327) = 255;  
  32.       
  33.     while (!seeds.empty())  
  34.     {  
  35.         Point seed = seeds.top();  
  36.         seeds.pop();  
  37.   
  38.         // 标记为已遍历过的点  
  39.         flagMat.at<uchar>(seed.y, seed.x) = 1;  
  40.   
  41.         // 遍历8邻域  
  42.         for (size_t i = 0; i < 8; i++)  
  43.         {  
  44.             int tmpx = seed.x + connects[i].x;  
  45.             int tmpy = seed.y + connects[i].y;  
  46.   
  47.             if (tmpx < 0 || tmpy < 0 || tmpx >= src.cols || tmpy >= src.rows)    
  48.                 continue;  
  49.             // 前景点且没有被标记过的点  
  50.             if (bin.at<uchar>(tmpy, tmpx) != 0 && flagMat.at<uchar>(tmpy, tmpx) == 0)   // 可将之前的threshold函数屏蔽
  51.             {                                                                                                         //使用if(bin.at<uchar>(tmpy,tmpx)>80&&flagMat.at<uchar>                                                                                                                                              //  (tmpy,tmpx)==0) 来代替之前的函数,根据这个规则进行区域生长;
  52.                 res.at<uchar>(tmpy, tmpx) = 255; // 生长  
  53.                 flagMat.at<uchar>(tmpy, tmpx) = 1; // 标记  
  54.                 seeds.push(Point(tmpx, tmpy)); // 种子压栈  
  55.             }  
  56.         }  
  57.     }  
  58.   
  59.     imshow("RES",res);  
  60.     imwrite("res.jpg", res);  
  61.     waitKey(0);  
  62.     return 1;  
  63. }  
posted @ 2017-05-19 14:41  james_blog  阅读(225)  评论(0)    收藏  举报