openCv学习笔记(七)-漫水填充算法详解

一 漫水填充算法描述

    1..1 、种子填充算法

         种子填充算法是从多边形区域内部的一点开始,由此出发找到区域内的所有像素。

         种子填充算法采用的边界定义是区域边界上所有像素具有某个特定的颜色值,区域内部所有像素均不取这一特定颜色,而边界外的像素则可具有与边界相同的颜色值。

         具体算法步骤:(1)标记种子(x,y)的像素点 (2)检测该点的颜色,若他与边界色和填充色均不同,就用填充色填   充该点,否则不填充 (3)检测相邻位置,继续(2)。这个过程延续到已经检测区域边界范围内的所有像素为止。

         当然在搜索的时候有两种检测相邻像素:四向连通和八向连通。四向连通即从区域上一点出发,通过四个方向上、下、左、右来检索。而八向连通加上了左上、左下、右上、右下四个方向。

       这种算法的有点是算法简单,易于实现,也可以填充带有内孔的平面区域。但是此算法需要更大的存储空间以实现栈结构,同一个像素多次入栈和出栈,效率低,运算量大。

     1.2、扫描线种子填充算法

       该算法属于种子填充算法,它是以扫描线上的区段为单位操作。所谓区段,就是一条扫描线上相连着的若干内部象素的集合。
     扫描线种子填充算法思想:首先填
充当前扫描线上的位于给定区域的一区段,然后确定于这一区段相邻的上下两条线上位于该区域内是否存在需要填充的新区段,如果存在,则依次把他们保存起来,反复这个过程,直到所保存的各区段都填充完毕。

        1.2.1、扫描线种子填充算法实现(有演示动画见http://hi.baidu.com/jimmywood1987/blog/item/8410d9d5e621bd209a502740.html)
    借助于堆栈,上述算法实现步骤如下:

  1、初始化堆栈。
  2、种子压入堆栈。
  3、while(堆栈非空)
    {
     (1)从堆栈弹出种子象素。
     (2)如果种子象素尚未填充,则:
      a.求出种子区段:xleft、xright;
      b.填充整个区段。
      c.检查相邻的上扫描线的xleft <= x <= xright区间内,是否存在需要填充的新区段,如果存在的话,则把每个新区段在xleft <= x <= xright范围内的最右边的象素,作为新的种子象素依次压入堆栈。
      d.检查相邻的下扫描线的xleft <= x <= xright区间内,是否存在需要填充的新区段,如果存在的话,则把每个新区段在xleft <= x <= xright范围内的最右边的象素,作为新的种子象素依次压入堆栈。

    }

   1.2.2改进算法

     原算法中, 种子虽然代表一个区段, 但种子实质上仍是一个象素, 我们必须在种子出栈的时候计算种子区段, 而这里有很大一部分计算是重复的. 而且, 原算法的扫描过程如果不用mask的话, 每次都会重复扫描父种子区段所在的扫描线, 而用mask的话又会额外增加开销

  所以, 对原算法的一个改进就是让种子携带更多的信息, 让种子不再是一个象素, 而是一个结构体. 该结构体包含以下信息: 种子区段的y坐标值, 区段的x开始与结束坐标, 父种子区段的方向(上或者下), 父种子区段的x开始与结束坐标.
struct seed{
    int y,
    int xleft,
    int xright,
    int parent_xleft,
    int parent_xright,
    bool is_parent_up
};

这样算法的具体实现变动如下

  1、初始化堆栈.
  2、将种子象素扩充成为种子区段(y, xleft, xright, xright+1, xrihgt, true), 填充种子区段, 并压入堆栈. (这里有一个构造父种子区段的技巧)
  3、while(堆栈非空)
    {
     (1)从堆栈弹出种子区段。
     (2)检查父种子区段所在的扫描线的xleft <= x <= parent_xleft和parent_xright <= x <= xright两个区间, 如果存在需要填充的新区段, 则将其填充并压入堆栈.
     (3)检查非父种子区段所在的扫描线的xleft <= x <= xright区间, 如果存在需要填充的新区段, 则将其填充并压入堆栈.
    }

另外, opencv里的种子填充算法跟以上方法大致相同, 不同的地方是opencv用了队列不是堆栈, 而且是由固定长度的数组来实现的循环队列, 其固定长度为 max(img_width, img_height)*2. 并且push与pop均使用宏来实现而没有使用函数. 用固定长度的数组来实现队列(或堆栈)意义是显然的, 能大大减少构造结构, 复制结构等操作, 可以大大提高效率.


二 漫水填充算法c语言实现

/* 漫水法填充标定实现
   copy from: http://blog.csdn.net/zhjx2314/article/details/1629702 


*/
  //像素值
 unsigned char pixel;
 //种子堆栈及指针
 Seed *Seeds;
 int StackPoint;
 //当前像素位置
 int iCurrentPixelx,iCurrentPixely;
  //分配种子空间 
 Seeds = new Seed[iWidth*iLength];
 
 //计算每个标定值的像素个数
 int count[251];
 for(i=1;i<252;i++)
 {  
	 count[i]=0; //初始化为0
 } 
 
    //滤波的阈值
 int yuzhi = 700;
 

 for (i=0;i<iWidth;i++)
 {
   for (j=0;j<iLength;j++)
   {  
		 if (grey_liantong.GetPixel(i,j)==0)  //当前像素为黑,对它进行漫水法标定
		 {
				//初始化种子
				 Seeds[1].x = i;
				 Seeds[1].y = j;
				 StackPoint = 1;
			 
				while( StackPoint != 0)
				{
				  //取出种子
				  iCurrentPixelx = Seeds[StackPoint].x;
				  iCurrentPixely = Seeds[StackPoint].y;
				  StackPoint--;
				        
				 
				  //取得当前指针处的像素值,注意要转换为unsigned char型
				  pixel = (unsigned char)grey_liantong.GetPixel(iCurrentPixelx,iCurrentPixely);
				 
				  //将当前点标定
				  grey_liantong.SetPixel(iCurrentPixelx,iCurrentPixely,flag);
						count[flag]++; //标定像素计数
				 
				  //判断左面的点,如果为黑,则压入堆栈
				  //注意防止越界
				  if(iCurrentPixelx > 1)
				  {
				   
				       //取得当前指针处的像素值,注意要转换为unsigned char型
					   pixel = (unsigned char)grey_liantong.GetPixel(iCurrentPixelx-1,iCurrentPixely);
					   if (pixel == 0)
					   {
							StackPoint++;
							Seeds[StackPoint].y = iCurrentPixely;
							Seeds[StackPoint].x = iCurrentPixelx - 1;
					   }
				  }
				 
				  //判断上面的点,如果为黑,则压入堆栈
				  //注意防止越界
				  if(iCurrentPixely < iLength - 1)
				  {
				   
					   //取得当前指针处的像素值,注意要转换为unsigned char型
					   pixel = (unsigned char)grey_liantong.GetPixel(iCurrentPixelx,iCurrentPixely+1);
					   if (pixel == 0)
					   {
							StackPoint++;
							Seeds[StackPoint].y = iCurrentPixely + 1;
							Seeds[StackPoint].x = iCurrentPixelx;
					   }
				  }
				 
				  //判断右面的点,如果为黑,则压入堆栈
				  //注意防止越界
				  if(iCurrentPixelx < iWidth - 1)
				  {
				   
					   //取得当前指针处的像素值,注意要转换为unsigned char型
					   pixel = (unsigned char)grey_liantong.GetPixel(iCurrentPixelx+1,iCurrentPixely);
					   if (pixel == 0)
					   {
							StackPoint++;
							Seeds[StackPoint].y = iCurrentPixely;
							Seeds[StackPoint].x = iCurrentPixelx + 1;
					   }
				  }
				 
				  //判断下面的点,如果为黑,则压入堆栈
				  //注意防止越界
				  if(iCurrentPixely > 1)
				  {
				   
					   //取得当前指针处的像素值,注意要转换为unsigned char型
					   pixel = (unsigned char)grey_liantong.GetPixel(iCurrentPixelx,iCurrentPixely-1);
					   if (pixel == 0)
					   {
							StackPoint++;
							Seeds[StackPoint].y = iCurrentPixely - 1;
							Seeds[StackPoint].x = iCurrentPixelx;
					   }
				  }
			  }//end while( StackPoint != 0)
			  flag = (flag + 7)%251+1;  //当前点连通区域标定后,改变标定值
		 }//end if  
   }//end for(i
 }//end for(j
 

 //释放堆栈
 delete Seeds;
    grey_res.Clone(grey_liantong); 


/*
   摘自:http://blog.sina.com.cn/s/blog_611a555e0100fcrq.html


	floodfill算法
2008-07-28 11:22
 

+ From wikipedia

Flood fill, also called seed fill, is an algorithm that determines the area connected to a given node in a multi-dimensional array. It is used in the "bucket" fill tool of paint programs to determine which parts of a bitmap to fill with color

+ the algorithms

The flood fill algorithm takes three parameters: a start node, a target color, and a replacement color. The algorithm looks for all nodes in the array which are connected to the start node by a path of the target color, and changes them to the replacement color. There are many ways in which the flood-fill algorithm can be structured, but they all make use of a queue or stack data structure, explicitly or implicitly.

从上面的算法介绍可知,凡是会搜索的同学就能很轻易地掌握floodfill。因为floodfill算法从大体而言可以细分为两种算法思想,一种是DFS,一种是BFS。以下讲介绍两大种常用的算法,并简单分析其中用到的dfs和bfs。

1. per-pixel fill (点点填充)

 

                                                           

recursive flood-fill with 4 directions                      recursive flood-fill with 8 directions

这两个有一个小区别,就是8方向的算法是在4方向的算法的基础上添加了四个方向(左上、左下、右上、右下),因此造成的结果是8方向的算法有可能会“leak through sloped edges of 1 pixel thick”。至于其它方面则是完全一样,下面所有的算法都是基于4方向的。

用dfs的搜索思想(递归)写的代码:

Flood-fill (node, target-color, replacement-color):
1. If the color of node is not equal to target-color, return.
2. Set the color of node to replacement-color.
3. Perform Flood-fill (one step to the west of node, target-color, replacement-color).
    Perform Flood-fill (one step to the east of node, target-color, replacement-color).
    Perform Flood-fill (one step to the north of node, target-color, replacement-color).
    Perform Flood-fill (one step to the south of node, target-color, replacement-color).
4. Return.

用bfs的搜索思想(队列)写的代码:

Flood-fill (node, target-color, replacement-color):
1. Set Q to the empty queue.
2. If the color of node is not equal to target-color, return.
3. Add node to the end of Q.
4. While "Q" is not empty:
5.     Set "n" equal to the first element of "Q"
6.     If the color of n is equal to target-color, set the color of n to replacement-color.
7.     Remove first element from "Q"
8.     If the color of the node to the west of n is target-color, set the color of that node to replacement-color, add that node to the end of Q.
9.     If the color of the node to the east of n is target-color, set the color of that node to replacement-color, add that node to the end of Q.
10.    If the color of the node to the north of n is target-color, set the color of that node to replacement-color, add that node to the end of Q.
11.    If the color of the node to the south of n is target-color, set the color of that node to replacement-color, add that node to the end of Q.
12. Return.

以上两种小算法的问题在于,如果填充的面积较大的话,程序很容易爆掉。究其原因,就是搜索的深度过大或队列的长度不够造成的。因此为了减少搜索深度或进队列的元素个数,可以用线方式代替点方式。而这样做还有一个好处就是填充速度的提高。
*/

	
	
//2. scanline fill (扫描线填充)
 

//stack friendly and fast floodfill algorithm(递归深搜的写法)

void floodFillScanline(int x, int y, int newColor, int oldColor)
{
    if(oldColor == newColor) return;
    if(screenBuffer[x][y] != oldColor) return;
     
    int y1;
   
    //draw current scanline from start position to the top
    y1 = y;
    while(y1 < h && screenBuffer[x][y1] == oldColor)
    {
        screenBuffer[x][y1] = newColor;
        y1++;
    }   
   
    //draw current scanline from start position to the bottom
    y1 = y - 1;
    while(y1 >= 0 && screenBuffer[x][y1] == oldColor)
    {
        screenBuffer[x][y1] = newColor;
        y1--;
    }
   
    //test for new scanlines to the left
    y1 = y;
    while(y1 < h && screenBuffer[x][y1] == newColor)
    {
        if(x > 0 && screenBuffer[x - 1][y1] == oldColor)
        {
            floodFillScanline(x - 1, y1, newColor, oldColor);
        }
        y1++;
    }
    y1 = y - 1;
    while(y1 >= 0 && screenBuffer[x][y1] == newColor)
    {
        if(x > 0 && screenBuffer[x - 1][y1] == oldColor)
        {
            floodFillScanline(x - 1, y1, newColor, oldColor);
        }
        y1--;
    }
   
    //test for new scanlines to the right
    y1 = y;
    while(y1 < h && screenBuffer[x][y1] == newColor)
    {
        if(x < w - 1 && screenBuffer[x + 1][y1] == oldColor)
        {          
            floodFillScanline(x + 1, y1, newColor, oldColor);
        }
        y1++;
    }
    y1 = y - 1;
    while(y1 >= 0 && screenBuffer[x][y1] == newColor)
    {
        if(x < w - 1 && screenBuffer[x + 1][y1] == oldColor)
        {
            floodFillScanline(x + 1, y1, newColor, oldColor);
        }
        y1--;
    }
}

//The scanline floodfill algorithm using our own stack routines, faster(广搜队列的写法)

void floodFillScanlineStack(int x, int y, int newColor, int oldColor)
{
    if(oldColor == newColor) return;
    emptyStack();
   
    int y1;
    bool spanLeft, spanRight;
   
    if(!push(x, y)) return;
   
    while(pop(x, y))
    {   
        y1 = y;
        while(y1 >= 0 && screenBuffer[x][y1] == oldColor) y1--;
        y1++;
        spanLeft = spanRight = 0;
        while(y1 < h && screenBuffer[x][y1] == oldColor )
        {
            screenBuffer[x][y1] = newColor;
            if(!spanLeft && x > 0 && screenBuffer[x - 1][y1] == oldColor)
            {
                if(!push(x - 1, y1)) return;
                spanLeft = 1;
            }
            else if(spanLeft && x > 0 && screenBuffer[x - 1][y1] != oldColor)
            {
                spanLeft = 0;
            }//写这一部分是防止因为同一列上有断开的段而造成的可能的“没填充”
            if(!spanRight && x < w - 1 && screenBuffer[x + 1][y1] == oldColor)
            {
                if(!push(x + 1, y1)) return;
                spanRight = 1;
            }
            else if(spanRight && x < w - 1 && screenBuffer[x + 1][y1] != oldColor)
            {
                spanRight = 0;
            } //写这一部分是防止因为同一列上有断开的段而造成的可能的“没填充”
            y1++;
        }
    }
}


//以上两个小算法填充的方向都是纵向填充,你也可以修改成横向填充。
 

以上是从网上摘录的,代码中有地址,不明白的话可以去它们的博客去看。。。

三 openCv中漫水填充算法

  

/*
 漫水填充算法:
 摘自:函数介绍 http://blog.csdn.net/superjimmy/article/details/6181528
      


FloodFill
用指定颜色填充一个连接域 

void cvFloodFill( CvArr* image, CvPoint seed_point, CvScalar new_val,CvScalar lo_diff=cvScalarAll(0), 
         CvScalar up_diff=cvScalarAll(0),CvConnectedComp* comp=NULL, int flags=4, CvArr* mask=NULL );
   #define CV_FLOODFILL_FIXED_RANGE (1 << 16)
   #define CV_FLOODFILL_MASK_ONLY (1 << 17)
	image 
	输入的 1- 或 3-通道, 8-比特或浮点数图像。输入的图像将被函数的操作所改变,除非你选择 CV_FLOODFILL_MASK_ONLY 选项 (见下面). 
	seed_point 
	开始的种子点. 
	new_val 
	新的重新绘制的象素值 
	lo_diff 
	当前观察象素值与其部件领域象素或者待加入该部件的种子象素之负差(Lower difference)的最大值。对 8-比特 彩色图像,它是一个 packed value. 
	up_diff 
	当前观察象素值与其部件领域象素或者待加入该部件的种子象素之正差(upper difference)的最大值。 对 8-比特 彩色图像,它是一个 packed value. 
	comp 
	指向部件结构体的指针,该结构体的内容由函数用重绘区域的信息填充。 
	flags 
	操作选项. 低位比特包含连通值, 4 (缺省) 或 8, 在函数执行连通过程中确定使用哪种邻域方式。高位比特可以是 0 或下面的开关选项的组合: 
	CV_FLOODFILL_FIXED_RANGE - 如果设置,则考虑当前象素与种子象素之间的差,否则考虑当前象素与其相邻象素的差。(范围是浮点数). 
	CV_FLOODFILL_MASK_ONLY - 如果设置,函数不填充原始图像 (忽略 new_val), 但填充掩模图像 (这种情况下 MASK 必须是非空的). 
	mask 
	运算掩模, 应该是单通道、8-比特图像, 长和宽上都比输入图像 image 大两个象素点。若非空,则函数使用且更新掩模, 所以使用者需对 mask 内容的初始化负责。填充不会经过 MASK 的非零象素, 例如,一个边缘检测子的输出可以用来作为 MASK 来阻止填充边缘。或者有可能在多次的函数调用中使用同一个 MASK,以保证填充的区域不会重叠。注意: 因为 MASK 比欲填充图像大,所以 mask 中与输入图像(x,y)像素点相对应的点具有(x+1,y+1)坐标。 
	函数 cvFloodFill 用指定颜色,从种子点开始填充一个连通域。连通性由象素值的接近程度来衡量。在点 (x, y) 的象素被认为是属于重新绘制的区域,如果: 

	src(x',y')-lo_diff<=src(x,y)<=src(x',y')+up_diff, 灰度图像,浮动范围 
	src(seed.x,seed.y)-lo<=src(x,y)<=src(seed.x,seed.y)+up_diff, 灰度图像,固定范围 
	src(x',y')r-lo_diffr<=src(x,y)r<=src(x',y')r+up_diffr 和 
	src(x',y')g-lo_diffg<=src(x,y)g<=src(x',y')g+up_diffg 和 
	src(x',y')b-lo_diffb<=src(x,y)b<=src(x',y')b+up_diffb, 彩色图像,浮动范围 
	src(seed.x,seed.y)r-lo_diffr<=src(x,y)r<=src(seed.x,seed.y)r+up_diffr 和 
	src(seed.x,seed.y)g-lo_diffg<=src(x,y)g<=src(seed.x,seed.y)g+up_diffg 和 
	src(seed.x,seed.y)b-lo_diffb<=src(x,y)b<=src(seed.x,seed.y)b+up_diffb, 彩色图像,固定范围 
	其中 src(x',y') 是象素邻域点的值。也就是说,为了被加入到连通域中,一个象素的彩色/亮度应该足够接近于: 

	它的邻域象素的彩色/亮度值,当该邻域点已经被认为属于浮动范围情况下的连通域。 
	固定范围情况下的种子点的彩色/亮度值 
*/
//rorger, 2010

#include "cv.h"
#include "highgui.h"

int main()
{
	cvNamedWindow("image");
	IplImage * src = cvLoadImage("D:\\openCV\\openCVProject\\openCv笔记\\openCv笔记\\test.jpg");
	
	IplImage * img=cvCreateImage(cvGetSize(src), 8, 3);
	cvCopyImage(src, img);
	
    cvFloodFill(
		img,
		cvPoint(54,82), //100,75,标记种子
		CV_RGB(255,0,0),
		cvScalar(20,30,40,0),
		cvScalar(20,30,40,0),
		NULL,
		4,
		NULL
		);

	
	cvShowImage("image", img);
	cvWaitKey(0);
	cvReleaseImage(&src);
	cvReleaseImage(&img);
	cvDestroyAllWindows();
	return 0;
}


对于漫水填充算法,自己对于openc中的实现也不知道是什么样,于是就看了一些源码,也没看明白,贴出来大家研究吧


/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"

typedef struct CvFFillSegment
{
    ushort y;
    ushort l;
    ushort r;
    ushort prevl;
    ushort prevr;
    short dir;
}
CvFFillSegment;

#define UP 1
#define DOWN -1

#define ICV_PUSH( Y, L, R, PREV_L, PREV_R, DIR )\
{                                               \
    tail->y = (ushort)(Y);                      \
    tail->l = (ushort)(L);                      \
    tail->r = (ushort)(R);                      \
    tail->prevl = (ushort)(PREV_L);             \
    tail->prevr = (ushort)(PREV_R);             \
    tail->dir = (short)(DIR);                   \
    if( ++tail >= buffer_end )                  \
        tail = buffer;                          \
}


#define ICV_POP( Y, L, R, PREV_L, PREV_R, DIR ) \
{                                               \
    Y = head->y;                                \
    L = head->l;                                \
    R = head->r;                                \
    PREV_L = head->prevl;                       \
    PREV_R = head->prevr;                       \
    DIR = head->dir;                            \
    if( ++head >= buffer_end )                  \
        head = buffer;                          \
}


#define ICV_EQ_C3( p1, p2 ) \
    ((p1)[0] == (p2)[0] && (p1)[1] == (p2)[1] && (p1)[2] == (p2)[2])

#define ICV_SET_C3( p, q ) \
    ((p)[0] = (q)[0], (p)[1] = (q)[1], (p)[2] = (q)[2])

/****************************************************************************************\
*              Simple Floodfill (repainting single-color connected component)            *
\****************************************************************************************/

static void
icvFloodFill_8u_CnIR( uchar* pImage, int step, CvSize roi, CvPoint seed,
                      uchar* _newVal, CvConnectedComp* region, int flags,
                      CvFFillSegment* buffer, int buffer_size, int cn )
{
    uchar* img = pImage + step * seed.y;
    int i, L, R;
    int area = 0;
    int val0[] = {0,0,0};
    uchar newVal[] = {0,0,0};
    int XMin, XMax, YMin = seed.y, YMax = seed.y;
    int _8_connectivity = (flags & 255) == 8;
    CvFFillSegment* buffer_end = buffer + buffer_size, *head = buffer, *tail = buffer;

    L = R = XMin = XMax = seed.x;

    if( cn == 1 )
    {
        val0[0] = img[L];
        newVal[0] = _newVal[0];

        img[L] = newVal[0];

        while( ++R < roi.width && img[R] == val0[0] )
            img[R] = newVal[0];

        while( --L >= 0 && img[L] == val0[0] )
            img[L] = newVal[0];
    }
    else
    {
        assert( cn == 3 );
        ICV_SET_C3( val0, img + L*3 );
        ICV_SET_C3( newVal, _newVal );

        ICV_SET_C3( img + L*3, newVal );

        while( --L >= 0 && ICV_EQ_C3( img + L*3, val0 ))
            ICV_SET_C3( img + L*3, newVal );

        while( ++R < roi.width && ICV_EQ_C3( img + R*3, val0 ))
            ICV_SET_C3( img + R*3, newVal );
    }

    XMax = --R;
    XMin = ++L;
    ICV_PUSH( seed.y, L, R, R + 1, R, UP );

    while( head != tail )
    {
        int k, YC, PL, PR, dir;
        ICV_POP( YC, L, R, PL, PR, dir );

        int data[][3] =
        {
            {-dir, L - _8_connectivity, R + _8_connectivity},
            {dir, L - _8_connectivity, PL - 1},
            {dir, PR + 1, R + _8_connectivity}
        };

        if( region )
        {
            area += R - L + 1;

            if( XMax < R ) XMax = R;
            if( XMin > L ) XMin = L;
            if( YMax < YC ) YMax = YC;
            if( YMin > YC ) YMin = YC;
        }

        for( k = 0/*(unsigned)(YC - dir) >= (unsigned)roi.height*/; k < 3; k++ )
        {
            dir = data[k][0];
            img = pImage + (YC + dir) * step;
            int left = data[k][1];
            int right = data[k][2];

            if( (unsigned)(YC + dir) >= (unsigned)roi.height )
                continue;

            if( cn == 1 )
                for( i = left; i <= right; i++ )
                {
                    if( (unsigned)i < (unsigned)roi.width && img[i] == val0[0] )
                    {
                        int j = i;
                        img[i] = newVal[0];
                        while( --j >= 0 && img[j] == val0[0] )
                            img[j] = newVal[0];

                        while( ++i < roi.width && img[i] == val0[0] )
                            img[i] = newVal[0];

                        ICV_PUSH( YC + dir, j+1, i-1, L, R, -dir );
                    }
                }
            else
                for( i = left; i <= right; i++ )
                {
                    if( (unsigned)i < (unsigned)roi.width && ICV_EQ_C3( img + i*3, val0 ))
                    {
                        int j = i;
                        ICV_SET_C3( img + i*3, newVal );
                        while( --j >= 0 && ICV_EQ_C3( img + j*3, val0 ))
                            ICV_SET_C3( img + j*3, newVal );

                        while( ++i < roi.width && ICV_EQ_C3( img + i*3, val0 ))
                            ICV_SET_C3( img + i*3, newVal );

                        ICV_PUSH( YC + dir, j+1, i-1, L, R, -dir );
                    }
                }
        }
    }

    if( region )
    {
        region->area = area;
        region->rect.x = XMin;
        region->rect.y = YMin;
        region->rect.width = XMax - XMin + 1;
        region->rect.height = YMax - YMin + 1;
        region->value = cvScalar(newVal[0], newVal[1], newVal[2], 0);
    }
}


/* because all the operations on floats that are done during non-gradient floodfill
   are just copying and comparison on equality,
   we can do the whole op on 32-bit integers instead */
static void
icvFloodFill_32f_CnIR( int* pImage, int step, CvSize roi, CvPoint seed,
                       int* _newVal, CvConnectedComp* region, int flags,
                       CvFFillSegment* buffer, int buffer_size, int cn )
{
    int* img = pImage + (step /= sizeof(pImage[0])) * seed.y;
    int i, L, R;
    int area = 0;
    int val0[] = {0,0,0};
    int newVal[] = {0,0,0};
    int XMin, XMax, YMin = seed.y, YMax = seed.y;
    int _8_connectivity = (flags & 255) == 8;
    CvFFillSegment* buffer_end = buffer + buffer_size, *head = buffer, *tail = buffer;

    L = R = XMin = XMax = seed.x;

    if( cn == 1 )
    {
        val0[0] = img[L];
        newVal[0] = _newVal[0];

        img[L] = newVal[0];

        while( ++R < roi.width && img[R] == val0[0] )
            img[R] = newVal[0];

        while( --L >= 0 && img[L] == val0[0] )
            img[L] = newVal[0];
    }
    else
    {
        assert( cn == 3 );
        ICV_SET_C3( val0, img + L*3 );
        ICV_SET_C3( newVal, _newVal );

        ICV_SET_C3( img + L*3, newVal );

        while( --L >= 0 && ICV_EQ_C3( img + L*3, val0 ))
            ICV_SET_C3( img + L*3, newVal );

        while( ++R < roi.width && ICV_EQ_C3( img + R*3, val0 ))
            ICV_SET_C3( img + R*3, newVal );
    }

    XMax = --R;
    XMin = ++L;
    ICV_PUSH( seed.y, L, R, R + 1, R, UP );

    while( head != tail )
    {
        int k, YC, PL, PR, dir;
        ICV_POP( YC, L, R, PL, PR, dir );

        int data[][3] =
        {
            {-dir, L - _8_connectivity, R + _8_connectivity},
            {dir, L - _8_connectivity, PL - 1},
            {dir, PR + 1, R + _8_connectivity}
        };

        if( region )
        {
            area += R - L + 1;

            if( XMax < R ) XMax = R;
            if( XMin > L ) XMin = L;
            if( YMax < YC ) YMax = YC;
            if( YMin > YC ) YMin = YC;
        }

        for( k = 0/*(unsigned)(YC - dir) >= (unsigned)roi.height*/; k < 3; k++ )
        {
            dir = data[k][0];
            img = pImage + (YC + dir) * step;
            int left = data[k][1];
            int right = data[k][2];

            if( (unsigned)(YC + dir) >= (unsigned)roi.height )
                continue;

            if( cn == 1 )
                for( i = left; i <= right; i++ )
                {
                    if( (unsigned)i < (unsigned)roi.width && img[i] == val0[0] )
                    {
                        int j = i;
                        img[i] = newVal[0];
                        while( --j >= 0 && img[j] == val0[0] )
                            img[j] = newVal[0];

                        while( ++i < roi.width && img[i] == val0[0] )
                            img[i] = newVal[0];

                        ICV_PUSH( YC + dir, j+1, i-1, L, R, -dir );
                    }
                }
            else
                for( i = left; i <= right; i++ )
                {
                    if( (unsigned)i < (unsigned)roi.width && ICV_EQ_C3( img + i*3, val0 ))
                    {
                        int j = i;
                        ICV_SET_C3( img + i*3, newVal );
                        while( --j >= 0 && ICV_EQ_C3( img + j*3, val0 ))
                            ICV_SET_C3( img + j*3, newVal );

                        while( ++i < roi.width && ICV_EQ_C3( img + i*3, val0 ))
                            ICV_SET_C3( img + i*3, newVal );

                        ICV_PUSH( YC + dir, j+1, i-1, L, R, -dir );
                    }
                }
        }
    }

    if( region )
    {
        Cv32suf v0, v1, v2;
        region->area = area;
        region->rect.x = XMin;
        region->rect.y = YMin;
        region->rect.width = XMax - XMin + 1;
        region->rect.height = YMax - YMin + 1;
        v0.i = newVal[0]; v1.i = newVal[1]; v2.i = newVal[2];
        region->value = cvScalar( v0.f, v1.f, v2.f );
    }
}

/****************************************************************************************\
*                                   Gradient Floodfill                                   *
\****************************************************************************************/

#define DIFF_INT_C1(p1,p2) ((unsigned)((p1)[0] - (p2)[0] + d_lw[0]) <= interval[0])

#define DIFF_INT_C3(p1,p2) ((unsigned)((p1)[0] - (p2)[0] + d_lw[0])<= interval[0] && \
                            (unsigned)((p1)[1] - (p2)[1] + d_lw[1])<= interval[1] && \
                            (unsigned)((p1)[2] - (p2)[2] + d_lw[2])<= interval[2])

#define DIFF_FLT_C1(p1,p2) (fabs((p1)[0] - (p2)[0] + d_lw[0]) <= interval[0])

#define DIFF_FLT_C3(p1,p2) (fabs((p1)[0] - (p2)[0] + d_lw[0]) <= interval[0] && \
                            fabs((p1)[1] - (p2)[1] + d_lw[1]) <= interval[1] && \
                            fabs((p1)[2] - (p2)[2] + d_lw[2]) <= interval[2])

static void
icvFloodFillGrad_8u_CnIR( uchar* pImage, int step, uchar* pMask, int maskStep,
                           CvSize /*roi*/, CvPoint seed, uchar* _newVal, uchar* _d_lw,
                           uchar* _d_up, CvConnectedComp* region, int flags,
                           CvFFillSegment* buffer, int buffer_size, int cn )
{
    uchar* img = pImage + step*seed.y;
    uchar* mask = (pMask += maskStep + 1) + maskStep*seed.y;
    int i, L, R;
    int area = 0;
    int sum[] = {0,0,0}, val0[] = {0,0,0};
    uchar newVal[] = {0,0,0};
    int d_lw[] = {0,0,0};
    unsigned interval[] = {0,0,0};
    int XMin, XMax, YMin = seed.y, YMax = seed.y;
    int _8_connectivity = (flags & 255) == 8;
    int fixedRange = flags & CV_FLOODFILL_FIXED_RANGE;
    int fillImage = (flags & CV_FLOODFILL_MASK_ONLY) == 0;
    uchar newMaskVal = (uchar)(flags & 0xff00 ? flags >> 8 : 1);
    CvFFillSegment* buffer_end = buffer + buffer_size, *head = buffer, *tail = buffer;

    L = R = seed.x;
    if( mask[L] )
        return;

    mask[L] = newMaskVal;

    for( i = 0; i < cn; i++ )
    {
        newVal[i] = _newVal[i];
        d_lw[i] = _d_lw[i];
        interval[i] = (unsigned)(_d_up[i] + _d_lw[i]);
        if( fixedRange )
            val0[i] = img[L*cn+i];
    }

    if( cn == 1 )
    {
        if( fixedRange )
        {
            while( !mask[R + 1] && DIFF_INT_C1( img + (R+1), val0 ))
                mask[++R] = newMaskVal;

            while( !mask[L - 1] && DIFF_INT_C1( img + (L-1), val0 ))
                mask[--L] = newMaskVal;
        }
        else
        {
            while( !mask[R + 1] && DIFF_INT_C1( img + (R+1), img + R ))
                mask[++R] = newMaskVal;

            while( !mask[L - 1] && DIFF_INT_C1( img + (L-1), img + L ))
                mask[--L] = newMaskVal;
        }
    }
    else
    {
        if( fixedRange )
        {
            while( !mask[R + 1] && DIFF_INT_C3( img + (R+1)*3, val0 ))
                mask[++R] = newMaskVal;

            while( !mask[L - 1] && DIFF_INT_C3( img + (L-1)*3, val0 ))
                mask[--L] = newMaskVal;
        }
        else
        {
            while( !mask[R + 1] && DIFF_INT_C3( img + (R+1)*3, img + R*3 ))
                mask[++R] = newMaskVal;

            while( !mask[L - 1] && DIFF_INT_C3( img + (L-1)*3, img + L*3 ))
                mask[--L] = newMaskVal;
        }
    }

    XMax = R;
    XMin = L;
    ICV_PUSH( seed.y, L, R, R + 1, R, UP );

    while( head != tail )
    {
        int k, YC, PL, PR, dir, curstep;
        ICV_POP( YC, L, R, PL, PR, dir );

        int data[][3] =
        {
            {-dir, L - _8_connectivity, R + _8_connectivity},
            {dir, L - _8_connectivity, PL - 1},
            {dir, PR + 1, R + _8_connectivity}
        };

        unsigned length = (unsigned)(R-L);

        if( region )
        {
            area += (int)length + 1;

            if( XMax < R ) XMax = R;
            if( XMin > L ) XMin = L;
            if( YMax < YC ) YMax = YC;
            if( YMin > YC ) YMin = YC;
        }

        if( cn == 1 )
        {
            for( k = 0; k < 3; k++ )
            {
                dir = data[k][0];
                curstep = dir * step;
                img = pImage + (YC + dir) * step;
                mask = pMask + (YC + dir) * maskStep;
                int left = data[k][1];
                int right = data[k][2];

                if( fixedRange )
                    for( i = left; i <= right; i++ )
                    {
                        if( !mask[i] && DIFF_INT_C1( img + i, val0 ))
                        {
                            int j = i;
                            mask[i] = newMaskVal;
                            while( !mask[--j] && DIFF_INT_C1( img + j, val0 ))
                                mask[j] = newMaskVal;

                            while( !mask[++i] && DIFF_INT_C1( img + i, val0 ))
                                mask[i] = newMaskVal;

                            ICV_PUSH( YC + dir, j+1, i-1, L, R, -dir );
                        }
                    }
                else if( !_8_connectivity )
                    for( i = left; i <= right; i++ )
                    {
                        if( !mask[i] && DIFF_INT_C1( img + i, img - curstep + i ))
                        {
                            int j = i;
                            mask[i] = newMaskVal;
                            while( !mask[--j] && DIFF_INT_C1( img + j, img + (j+1) ))
                                mask[j] = newMaskVal;

                            while( !mask[++i] &&
                                   (DIFF_INT_C1( img + i, img + (i-1) ) ||
                                   (DIFF_INT_C1( img + i, img + i - curstep) && i <= R)))
                                mask[i] = newMaskVal;

                            ICV_PUSH( YC + dir, j+1, i-1, L, R, -dir );
                        }
                    }
                else
                    for( i = left; i <= right; i++ )
                    {
                        int idx, val[1];

                        if( !mask[i] &&
                            (((val[0] = img[i],
                            (unsigned)(idx = i-L-1) <= length) &&
                            DIFF_INT_C1( val, img - curstep + (i-1))) ||
                            ((unsigned)(++idx) <= length &&
                            DIFF_INT_C1( val, img - curstep + i )) ||
                            ((unsigned)(++idx) <= length &&
                            DIFF_INT_C1( val, img - curstep + (i+1) ))))
                        {
                            int j = i;
                            mask[i] = newMaskVal;
                            while( !mask[--j] && DIFF_INT_C1( img + j, img + (j+1) ))
                                mask[j] = newMaskVal;

                            while( !mask[++i] &&
                                   ((val[0] = img[i],
                                   DIFF_INT_C1( val, img + (i-1) )) ||
                                   (((unsigned)(idx = i-L-1) <= length &&
                                   DIFF_INT_C1( val, img - curstep + (i-1) ))) ||
                                   ((unsigned)(++idx) <= length &&
                                   DIFF_INT_C1( val, img - curstep + i )) ||
                                   ((unsigned)(++idx) <= length &&
                                   DIFF_INT_C1( val, img - curstep + (i+1) ))))
                                mask[i] = newMaskVal;

                            ICV_PUSH( YC + dir, j+1, i-1, L, R, -dir );
                        }
                    }
            }

            img = pImage + YC * step;
            if( fillImage )
                for( i = L; i <= R; i++ )
                    img[i] = newVal[0];
            else if( region )
                for( i = L; i <= R; i++ )
                    sum[0] += img[i];
        }
        else
        {
            for( k = 0; k < 3; k++ )
            {
                dir = data[k][0];
                curstep = dir * step;
                img = pImage + (YC + dir) * step;
                mask = pMask + (YC + dir) * maskStep;
                int left = data[k][1];
                int right = data[k][2];

                if( fixedRange )
                    for( i = left; i <= right; i++ )
                    {
                        if( !mask[i] && DIFF_INT_C3( img + i*3, val0 ))
                        {
                            int j = i;
                            mask[i] = newMaskVal;
                            while( !mask[--j] && DIFF_INT_C3( img + j*3, val0 ))
                                mask[j] = newMaskVal;

                            while( !mask[++i] && DIFF_INT_C3( img + i*3, val0 ))
                                mask[i] = newMaskVal;

                            ICV_PUSH( YC + dir, j+1, i-1, L, R, -dir );
                        }
                    }
                else if( !_8_connectivity )
                    for( i = left; i <= right; i++ )
                    {
                        if( !mask[i] && DIFF_INT_C3( img + i*3, img - curstep + i*3 ))
                        {
                            int j = i;
                            mask[i] = newMaskVal;
                            while( !mask[--j] && DIFF_INT_C3( img + j*3, img + (j+1)*3 ))
                                mask[j] = newMaskVal;

                            while( !mask[++i] &&
                                   (DIFF_INT_C3( img + i*3, img + (i-1)*3 ) ||
                                   (DIFF_INT_C3( img + i*3, img + i*3 - curstep) && i <= R)))
                                mask[i] = newMaskVal;

                            ICV_PUSH( YC + dir, j+1, i-1, L, R, -dir );
                        }
                    }
                else
                    for( i = left; i <= right; i++ )
                    {
                        int idx, val[3];

                        if( !mask[i] &&
                            (((ICV_SET_C3( val, img+i*3 ),
                            (unsigned)(idx = i-L-1) <= length) &&
                            DIFF_INT_C3( val, img - curstep + (i-1)*3 )) ||
                            ((unsigned)(++idx) <= length &&
                            DIFF_INT_C3( val, img - curstep + i*3 )) ||
                            ((unsigned)(++idx) <= length &&
                            DIFF_INT_C3( val, img - curstep + (i+1)*3 ))))
                        {
                            int j = i;
                            mask[i] = newMaskVal;
                            while( !mask[--j] && DIFF_INT_C3( img + j*3, img + (j+1)*3 ))
                                mask[j] = newMaskVal;

                            while( !mask[++i] &&
                                   ((ICV_SET_C3( val, img + i*3 ),
                                   DIFF_INT_C3( val, img + (i-1)*3 )) ||
                                   (((unsigned)(idx = i-L-1) <= length &&
                                   DIFF_INT_C3( val, img - curstep + (i-1)*3 ))) ||
                                   ((unsigned)(++idx) <= length &&
                                   DIFF_INT_C3( val, img - curstep + i*3 )) ||
                                   ((unsigned)(++idx) <= length &&
                                   DIFF_INT_C3( val, img - curstep + (i+1)*3 ))))
                                mask[i] = newMaskVal;

                            ICV_PUSH( YC + dir, j+1, i-1, L, R, -dir );
                        }
                    }
            }

            img = pImage + YC * step;
            if( fillImage )
                for( i = L; i <= R; i++ )
                    ICV_SET_C3( img + i*3, newVal );
            else if( region )
                for( i = L; i <= R; i++ )
                {
                    sum[0] += img[i*3];
                    sum[1] += img[i*3+1];
                    sum[2] += img[i*3+2];
                }
        }
    }

    if( region )
    {
        region->area = area;
        region->rect.x = XMin;
        region->rect.y = YMin;
        region->rect.width = XMax - XMin + 1;
        region->rect.height = YMax - YMin + 1;

        if( fillImage )
            region->value = cvScalar(newVal[0], newVal[1], newVal[2]);
        else
        {
            double iarea = area ? 1./area : 0;
            region->value = cvScalar(sum[0]*iarea, sum[1]*iarea, sum[2]*iarea);
        }
    }
}


static void
icvFloodFillGrad_32f_CnIR( float* pImage, int step, uchar* pMask, int maskStep,
                           CvSize /*roi*/, CvPoint seed, float* _newVal, float* _d_lw,
                           float* _d_up, CvConnectedComp* region, int flags,
                           CvFFillSegment* buffer, int buffer_size, int cn )
{
    float* img = pImage + (step /= sizeof(float))*seed.y;
    uchar* mask = (pMask += maskStep + 1) + maskStep*seed.y;
    int i, L, R;
    int area = 0;
    double sum[] = {0,0,0}, val0[] = {0,0,0};
    float newVal[] = {0,0,0};
    float d_lw[] = {0,0,0};
    float interval[] = {0,0,0};
    int XMin, XMax, YMin = seed.y, YMax = seed.y;
    int _8_connectivity = (flags & 255) == 8;
    int fixedRange = flags & CV_FLOODFILL_FIXED_RANGE;
    int fillImage = (flags & CV_FLOODFILL_MASK_ONLY) == 0;
    uchar newMaskVal = (uchar)(flags & 0xff00 ? flags >> 8 : 1);
    CvFFillSegment* buffer_end = buffer + buffer_size, *head = buffer, *tail = buffer;

    L = R = seed.x;
    if( mask[L] )
        return;

    mask[L] = newMaskVal;

    for( i = 0; i < cn; i++ )
    {
        newVal[i] = _newVal[i];
        d_lw[i] = 0.5f*(_d_lw[i] - _d_up[i]);
        interval[i] = 0.5f*(_d_lw[i] + _d_up[i]);
        if( fixedRange )
            val0[i] = img[L*cn+i];
    }

    if( cn == 1 )
    {
        if( fixedRange )
        {
            while( !mask[R + 1] && DIFF_FLT_C1( img + (R+1), val0 ))
                mask[++R] = newMaskVal;

            while( !mask[L - 1] && DIFF_FLT_C1( img + (L-1), val0 ))
                mask[--L] = newMaskVal;
        }
        else
        {
            while( !mask[R + 1] && DIFF_FLT_C1( img + (R+1), img + R ))
                mask[++R] = newMaskVal;

            while( !mask[L - 1] && DIFF_FLT_C1( img + (L-1), img + L ))
                mask[--L] = newMaskVal;
        }
    }
    else
    {
        if( fixedRange )
        {
            while( !mask[R + 1] && DIFF_FLT_C3( img + (R+1)*3, val0 ))
                mask[++R] = newMaskVal;

            while( !mask[L - 1] && DIFF_FLT_C3( img + (L-1)*3, val0 ))
                mask[--L] = newMaskVal;
        }
        else
        {
            while( !mask[R + 1] && DIFF_FLT_C3( img + (R+1)*3, img + R*3 ))
                mask[++R] = newMaskVal;

            while( !mask[L - 1] && DIFF_FLT_C3( img + (L-1)*3, img + L*3 ))
                mask[--L] = newMaskVal;
        }
    }

    XMax = R;
    XMin = L;
    ICV_PUSH( seed.y, L, R, R + 1, R, UP );

    while( head != tail )
    {
        int k, YC, PL, PR, dir, curstep;
        ICV_POP( YC, L, R, PL, PR, dir );

        int data[][3] =
        {
            {-dir, L - _8_connectivity, R + _8_connectivity},
            {dir, L - _8_connectivity, PL - 1},
            {dir, PR + 1, R + _8_connectivity}
        };

        unsigned length = (unsigned)(R-L);

        if( region )
        {
            area += (int)length + 1;

            if( XMax < R ) XMax = R;
            if( XMin > L ) XMin = L;
            if( YMax < YC ) YMax = YC;
            if( YMin > YC ) YMin = YC;
        }

        if( cn == 1 )
        {
            for( k = 0; k < 3; k++ )
            {
                dir = data[k][0];
                curstep = dir * step;
                img = pImage + (YC + dir) * step;
                mask = pMask + (YC + dir) * maskStep;
                int left = data[k][1];
                int right = data[k][2];

                if( fixedRange )
                    for( i = left; i <= right; i++ )
                    {
                        if( !mask[i] && DIFF_FLT_C1( img + i, val0 ))
                        {
                            int j = i;
                            mask[i] = newMaskVal;
                            while( !mask[--j] && DIFF_FLT_C1( img + j, val0 ))
                                mask[j] = newMaskVal;

                            while( !mask[++i] && DIFF_FLT_C1( img + i, val0 ))
                                mask[i] = newMaskVal;

                            ICV_PUSH( YC + dir, j+1, i-1, L, R, -dir );
                        }
                    }
                else if( !_8_connectivity )
                    for( i = left; i <= right; i++ )
                    {
                        if( !mask[i] && DIFF_FLT_C1( img + i, img - curstep + i ))
                        {
                            int j = i;
                            mask[i] = newMaskVal;
                            while( !mask[--j] && DIFF_FLT_C1( img + j, img + (j+1) ))
                                mask[j] = newMaskVal;

                            while( !mask[++i] &&
                                   (DIFF_FLT_C1( img + i, img + (i-1) ) ||
                                   (DIFF_FLT_C1( img + i, img + i - curstep) && i <= R)))
                                mask[i] = newMaskVal;

                            ICV_PUSH( YC + dir, j+1, i-1, L, R, -dir );
                        }
                    }
                else
                    for( i = left; i <= right; i++ )
                    {
                        int idx;
                        float val[1];

                        if( !mask[i] &&
                            (((val[0] = img[i],
                            (unsigned)(idx = i-L-1) <= length) &&
                            DIFF_FLT_C1( val, img - curstep + (i-1) )) ||
                            ((unsigned)(++idx) <= length &&
                            DIFF_FLT_C1( val, img - curstep + i )) ||
                            ((unsigned)(++idx) <= length &&
                            DIFF_FLT_C1( val, img - curstep + (i+1) ))))
                        {
                            int j = i;
                            mask[i] = newMaskVal;
                            while( !mask[--j] && DIFF_FLT_C1( img + j, img + (j+1) ))
                                mask[j] = newMaskVal;

                            while( !mask[++i] &&
                                   ((val[0] = img[i],
                                   DIFF_FLT_C1( val, img + (i-1) )) ||
                                   (((unsigned)(idx = i-L-1) <= length &&
                                   DIFF_FLT_C1( val, img - curstep + (i-1) ))) ||
                                   ((unsigned)(++idx) <= length &&
                                   DIFF_FLT_C1( val, img - curstep + i )) ||
                                   ((unsigned)(++idx) <= length &&
                                   DIFF_FLT_C1( val, img - curstep + (i+1) ))))
                                mask[i] = newMaskVal;

                            ICV_PUSH( YC + dir, j+1, i-1, L, R, -dir );
                        }
                    }
            }

            img = pImage + YC * step;
            if( fillImage )
                for( i = L; i <= R; i++ )
                    img[i] = newVal[0];
            else if( region )
                for( i = L; i <= R; i++ )
                    sum[0] += img[i];
        }
        else
        {
            for( k = 0; k < 3; k++ )
            {
                dir = data[k][0];
                curstep = dir * step;
                img = pImage + (YC + dir) * step;
                mask = pMask + (YC + dir) * maskStep;
                int left = data[k][1];
                int right = data[k][2];

                if( fixedRange )
                    for( i = left; i <= right; i++ )
                    {
                        if( !mask[i] && DIFF_FLT_C3( img + i*3, val0 ))
                        {
                            int j = i;
                            mask[i] = newMaskVal;
                            while( !mask[--j] && DIFF_FLT_C3( img + j*3, val0 ))
                                mask[j] = newMaskVal;

                            while( !mask[++i] && DIFF_FLT_C3( img + i*3, val0 ))
                                mask[i] = newMaskVal;

                            ICV_PUSH( YC + dir, j+1, i-1, L, R, -dir );
                        }
                    }
                else if( !_8_connectivity )
                    for( i = left; i <= right; i++ )
                    {
                        if( !mask[i] && DIFF_FLT_C3( img + i*3, img - curstep + i*3 ))
                        {
                            int j = i;
                            mask[i] = newMaskVal;
                            while( !mask[--j] && DIFF_FLT_C3( img + j*3, img + (j+1)*3 ))
                                mask[j] = newMaskVal;

                            while( !mask[++i] &&
                                   (DIFF_FLT_C3( img + i*3, img + (i-1)*3 ) ||
                                   (DIFF_FLT_C3( img + i*3, img + i*3 - curstep) && i <= R)))
                                mask[i] = newMaskVal;

                            ICV_PUSH( YC + dir, j+1, i-1, L, R, -dir );
                        }
                    }
                else
                    for( i = left; i <= right; i++ )
                    {
                        int idx;
                        float val[3];

                        if( !mask[i] &&
                            (((ICV_SET_C3( val, img+i*3 ),
                            (unsigned)(idx = i-L-1) <= length) &&
                            DIFF_FLT_C3( val, img - curstep + (i-1)*3 )) ||
                            ((unsigned)(++idx) <= length &&
                            DIFF_FLT_C3( val, img - curstep + i*3 )) ||
                            ((unsigned)(++idx) <= length &&
                            DIFF_FLT_C3( val, img - curstep + (i+1)*3 ))))
                        {
                            int j = i;
                            mask[i] = newMaskVal;
                            while( !mask[--j] && DIFF_FLT_C3( img + j*3, img + (j+1)*3 ))
                                mask[j] = newMaskVal;

                            while( !mask[++i] &&
                                   ((ICV_SET_C3( val, img + i*3 ),
                                   DIFF_FLT_C3( val, img + (i-1)*3 )) ||
                                   (((unsigned)(idx = i-L-1) <= length &&
                                   DIFF_FLT_C3( val, img - curstep + (i-1)*3 ))) ||
                                   ((unsigned)(++idx) <= length &&
                                   DIFF_FLT_C3( val, img - curstep + i*3 )) ||
                                   ((unsigned)(++idx) <= length &&
                                   DIFF_FLT_C3( val, img - curstep + (i+1)*3 ))))
                                mask[i] = newMaskVal;

                            ICV_PUSH( YC + dir, j+1, i-1, L, R, -dir );
                        }
                    }
            }

            img = pImage + YC * step;
            if( fillImage )
                for( i = L; i <= R; i++ )
                    ICV_SET_C3( img + i*3, newVal );
            else if( region )
                for( i = L; i <= R; i++ )
                {
                    sum[0] += img[i*3];
                    sum[1] += img[i*3+1];
                    sum[2] += img[i*3+2];
                }
        }
    }

    if( region )
    {
        region->area = area;
        region->rect.x = XMin;
        region->rect.y = YMin;
        region->rect.width = XMax - XMin + 1;
        region->rect.height = YMax - YMin + 1;

        if( fillImage )
            region->value = cvScalar(newVal[0], newVal[1], newVal[2]);
        else
        {
            double iarea = area ? 1./area : 0;
            region->value = cvScalar(sum[0]*iarea, sum[1]*iarea, sum[2]*iarea);
        }
    }
}


/****************************************************************************************\
*                                    External Functions                                  *
\****************************************************************************************/

typedef  void (*CvFloodFillFunc)(
               void* img, int step, CvSize size, CvPoint seed, void* newval,
               CvConnectedComp* comp, int flags, void* buffer, int buffer_size, int cn );

typedef  void (*CvFloodFillGradFunc)(
               void* img, int step, uchar* mask, int maskStep, CvSize size,
               CvPoint seed, void* newval, void* d_lw, void* d_up, void* ccomp,
               int flags, void* buffer, int buffer_size, int cn );

CV_IMPL void
cvFloodFill( CvArr* arr, CvPoint seed_point,
             CvScalar newVal, CvScalar lo_diff, CvScalar up_diff,
             CvConnectedComp* comp, int flags, CvArr* maskarr )
{
    cv::Ptr<CvMat> tempMask;
    cv::AutoBuffer<CvFFillSegment> buffer;
    
    if( comp )
        memset( comp, 0, sizeof(*comp) );

    int i, type, depth, cn, is_simple;
    int buffer_size, connectivity = flags & 255;
    double nv_buf[4] = {0,0,0,0};
    union { uchar b[4]; float f[4]; } ld_buf, ud_buf;
    CvMat stub, *img = cvGetMat(arr, &stub);
    CvMat maskstub, *mask = (CvMat*)maskarr;
    CvSize size;

    type = CV_MAT_TYPE( img->type );
    depth = CV_MAT_DEPTH(type);
    cn = CV_MAT_CN(type);

    if( connectivity == 0 )
        connectivity = 4;
    else if( connectivity != 4 && connectivity != 8 )
        CV_Error( CV_StsBadFlag, "Connectivity must be 4, 0(=4) or 8" );

    is_simple = mask == 0 && (flags & CV_FLOODFILL_MASK_ONLY) == 0;

    for( i = 0; i < cn; i++ )
    {
        if( lo_diff.val[i] < 0 || up_diff.val[i] < 0 )
            CV_Error( CV_StsBadArg, "lo_diff and up_diff must be non-negative" );
        is_simple &= fabs(lo_diff.val[i]) < DBL_EPSILON && fabs(up_diff.val[i]) < DBL_EPSILON;
    }

    size = cvGetMatSize( img );

    if( (unsigned)seed_point.x >= (unsigned)size.width ||
        (unsigned)seed_point.y >= (unsigned)size.height )
        CV_Error( CV_StsOutOfRange, "Seed point is outside of image" );

    cvScalarToRawData( &newVal, &nv_buf, type, 0 );
    buffer_size = MAX( size.width, size.height )*2;
    buffer.allocate( buffer_size );

    if( is_simple )
    {
        int elem_size = CV_ELEM_SIZE(type);
        const uchar* seed_ptr = img->data.ptr + img->step*seed_point.y + elem_size*seed_point.x;
        CvFloodFillFunc func =
            type == CV_8UC1 || type == CV_8UC3 ? (CvFloodFillFunc)icvFloodFill_8u_CnIR :
            type == CV_32FC1 || type == CV_32FC3 ? (CvFloodFillFunc)icvFloodFill_32f_CnIR : 0;
        if( !func )
            CV_Error( CV_StsUnsupportedFormat, "" );
        // check if the new value is different from the current value at the seed point.
        // if they are exactly the same, use the generic version with mask to avoid infinite loops.
        for( i = 0; i < elem_size; i++ )
            if( seed_ptr[i] != ((uchar*)nv_buf)[i] )
                break;
        if( i < elem_size )
        {
            func( img->data.ptr, img->step, size,
                  seed_point, &nv_buf, comp, flags,
                  buffer, buffer_size, cn );
            return;
        }
    }

    CvFloodFillGradFunc func = 
        type == CV_8UC1 || type == CV_8UC3 ? (CvFloodFillGradFunc)icvFloodFillGrad_8u_CnIR :
        type == CV_32FC1 || type == CV_32FC3 ? (CvFloodFillGradFunc)icvFloodFillGrad_32f_CnIR : 0;
    if( !func )
        CV_Error( CV_StsUnsupportedFormat, "" );
    
    if( !mask )
    {
        /* created mask will be 8-byte aligned */
        tempMask = cvCreateMat( size.height + 2, (size.width + 9) & -8, CV_8UC1 );
        mask = tempMask;
    }
    else
    {
        mask = cvGetMat( mask, &maskstub );
        if( !CV_IS_MASK_ARR( mask ))
            CV_Error( CV_StsBadMask, "" );

        if( mask->width != size.width + 2 || mask->height != size.height + 2 )
            CV_Error( CV_StsUnmatchedSizes, "mask must be 2 pixel wider "
                                   "and 2 pixel taller than filled image" );
    }

    int width = tempMask ? mask->step : size.width + 2;
    uchar* mask_row = mask->data.ptr + mask->step;
    memset( mask_row - mask->step, 1, width );

    for( i = 1; i <= size.height; i++, mask_row += mask->step )
    {
        if( tempMask )
            memset( mask_row, 0, width );
        mask_row[0] = mask_row[size.width+1] = (uchar)1;
    }
    memset( mask_row, 1, width );

    if( depth == CV_8U )
        for( i = 0; i < cn; i++ )
        {
            int t = cvFloor(lo_diff.val[i]);
            ld_buf.b[i] = CV_CAST_8U(t);
            t = cvFloor(up_diff.val[i]);
            ud_buf.b[i] = CV_CAST_8U(t);
        }
    else
        for( i = 0; i < cn; i++ )
        {
            ld_buf.f[i] = (float)lo_diff.val[i];
            ud_buf.f[i] = (float)up_diff.val[i];
        }

    func( img->data.ptr, img->step, mask->data.ptr, mask->step,
          size, seed_point, &nv_buf, ld_buf.f, ud_buf.f,
          comp, flags, buffer, buffer_size, cn );
}


int cv::floodFill( InputOutputArray _image, Point seedPoint,
                   Scalar newVal, Rect* rect,
                   Scalar loDiff, Scalar upDiff, int flags )
{
    CvConnectedComp ccomp;
    CvMat c_image = _image.getMat();
    cvFloodFill(&c_image, seedPoint, newVal, loDiff, upDiff, &ccomp, flags, 0);
    if( rect )
        *rect = ccomp.rect;
    return cvRound(ccomp.area);
}

int cv::floodFill( InputOutputArray _image, InputOutputArray _mask,
                   Point seedPoint, Scalar newVal, Rect* rect, 
                   Scalar loDiff, Scalar upDiff, int flags )
{
    CvConnectedComp ccomp;
    CvMat c_image = _image.getMat(), c_mask = _mask.getMat();
    cvFloodFill(&c_image, seedPoint, newVal, loDiff, upDiff, &ccomp, flags, c_mask.data.ptr ? &c_mask : 0);
    if( rect )
        *rect = ccomp.rect;
    return cvRound(ccomp.area);
}

/* End of file. */


参考:

1  http://hi.baidu.com/jimmywood1987/blog/item/8410d9d5e621bd209a502740.html

2  http://sjy.gxqzu.edu.cn/sjx/sjxbk3/newsshow.aspx?n_id=49

3  http://blog.sina.com.cn/s/blog_611a555e0100fcrq.html

4  http://blog.csdn.net/zhjx2314/article/details/1629702

    

       

你可能感兴趣的:(Algorithm,c,算法,image,buffer)