自己用Qt實現的地區生長法

來源:互聯網
上載者:User

 int threshold =door;//閾值

    int height = image.height(); // 映像高度
    int width  =  image.width();     //寬度
    QImage image2 = image;
    for(int i = 0;i<width;i++)
        for(int j = 0;j<height;j++)
            image2.setPixel(i,j,qRgb(0,0,0));//初始化為0

    //二維數組代表中心像素點的8鄰域座標,第一列為x方向的位移,第二列為y方向的位移
    int direction[8][2]={{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};
    // 定義堆棧,假定進棧的像素最多為映像總像素的三分之一左右。
    int  max=height*width;
    QPoint stack[max];
    //棧頂指標
    int top;
    //當前正在處理的點和彈出的點
    QPoint currentPoint,popPoint;
    //迴圈變數,遍曆array數組的一維下標
    int k;
    //標記變數
    int label;
    int x,y;
    x=curpo.x();
    y=curpo.y();
    //臨時變數
    int temp1,temp2;
    //記錄種子像素的灰階值
    temp1 = QRgb2Rgb(image.pixel(x,y));
    //將給定種子點標記為255,入棧
    image2.setPixel(x,y,qRgb(255,255,255));
    top = 0;//堆棧向上生長
    stack[top].setX(x);
    stack[top].setY(y);
    //堆棧
    while(top>-1&&top<max)
    {
       //彈出棧頂元素,該元素已經生長過
       popPoint.setX(stack[top].x());
       popPoint.setY(stack[top].y());
       top--;
       //考察彈出像素周圍是否有生長的像素
       for(k=0;k<8;k++)
       {
          currentPoint.setX(popPoint.x()+direction[k][0]);
          currentPoint.setY(popPoint.y()+direction[k][1]);
          //如果考察的點不在映像內,則跳過
          if((currentPoint.x()<0)||(currentPoint.x()>width-1)||
             (currentPoint.y()<0)||(currentPoint.y()>height-1))
             continue;
          //該點標號
          label = QRgb2Rgb(image2.pixel(currentPoint.x(),currentPoint.y()));
          //彈出點周圍有尚沒生長的點
             if(label==0)
          {
             temp2 = QRgb2Rgb(image.pixel(currentPoint.x(),currentPoint.y()));
             //如果當前被考察的像素灰階值與種子點灰階值之差小於給定閾值
             //則認為相似,作進棧處理
             if(abs(temp1-temp2)<threshold)
             {
                //給該點置生長標記255
                 image2.setPixel(currentPoint.x(),currentPoint.y(),qRgb(255,255,255));
                top++;
                stack[top].setX(currentPoint.x());
                stack[top].setY(currentPoint.y());
             }
          }
       }
    }
    image3=image2;
    image2=image2.scaled(ui->label_3->width(),ui->label_3->height(),Qt::IgnoreAspectRatio);
    ui->label_3->setPixmap(QPixmap::fromImage(image2));

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.