魔棒工具--RegionGrow算法簡介


  ps里面的魔棒工具非常好用,是圖像處理中非常常用的一個工具,它現在已經是我的c++工具箱中很重要的一員了,我會在以后的時間里把我的工具箱逐漸介紹給大家。
  魔棒工具的核心算法是RegionGrow區域成長法,它的概念很簡單,首先在要處理的圖片上選取一個種子點,然后以此點為起點,向四周輻射形成一個區域。最初成長區域只有種子點這一個點,然后不斷把周圍的點歸並入該成長區域,條件是該點的值與成長區域邊界點的值之差小於閾值。當成長區域不能再繼續擴大時,算法停止。
 

 
算法說明:
  區域成長法的思想很好理解,代碼實現對於初學者有一定難度。對於滿足條件的像素點,函數會把它們一個個的壓入隊列的尾部,然后從隊列的頭部一個個的取出來,形成成長區域。M是一個點名冊,用來記錄每一個像素是否被處理過。start和end用來記錄隊列的頭和尾,當start==end時,說明所有所有像素已經處理完,函數結束。
 
參數說明:
src: 輸入的單通道圖像。
dst: 輸出的單通道圖像,與輸入同大小,必須提前開空間。
seedx, seedy:  種子點坐標
threshold:  容差
flag: 0/1 表示搜索方式是 8/4 鄰域
 
struct Node { int x; int y; Node* next; }; void MyTreasureBox::RegionGrow(const IplImage* src, IplImage* dst, int seedx, int seedy, int threshold, bool flag) { if(!src || src->nChannels != 1)return ; int width = src->width; int height = src->height; int srcwidthstep = src->widthStep; uchar* img = (uchar*)src->imageData; //成長區域
 cvZero(dst); //標記每個像素點是否被計算過
    IplImage* M = cvCreateImage(cvSize(width, height), 8, 1); int Mwidthstep = M->widthStep; cvZero(M); M->imageData[seedy * Mwidthstep + seedx] = 1;    //種子點位置為1,其它位置為0
 CvScalar cur = CV_RGB(255,255,255); cvSet2D(dst, seedy, seedx, cur); //隊列的兩端
    int start = 0; int end = 1; Node *queue = new Node; queue->x = seedx; queue->y = seedy; queue->next = NULL; Node *first = queue; Node *last = queue; while (end - start > 0) { int x = first->x; int y = first->y; uchar pixel = (uchar)img[y * srcwidthstep + x]; for (int yy = -1; yy<=1; yy++) { for (int xx = -1; xx<=1; xx++) { if(flag) if ( abs(yy) && abs(xx)) continue; int cx = x + xx; int cy = y + yy; if (cx >= 0 && cx <width && cy >=0 && cy < height) { if (abs(img[cy * srcwidthstep + cx] - pixel) <= threshold && M->imageData[cy * Mwidthstep + cx] != 1) { Node *node = new Node; node->x = cx; node->y = cy; node->next = NULL; end++; last->next = node; last = node; M->imageData[cy * Mwidthstep + cx] = 1; cvSet2D(dst, cy, cx, cur); } } } } Node* temp = first; first = first->next; delete temp; start++; } cvReleaseImage(&M); }




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM