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));