实验三区域填充算法的实现
一、实验目的和要求:
1、掌握区域填充算法基本知识
2、理解区域的表示和类型,能正确区分四连通和八连通的区域
3、了解区域填充的实现原理,利用Microsoft Visual C++ 6.0或win-TC实现区
域种子填充的递归算法。
二、实验内容:
1、编程完成区域填色
2、利用画线函数,在屏幕上定义一个封闭区域。
3、利用以下两种种子填充算法,填充上述步骤中定义的区域
(1)边界表示的四连通区域种子填充的实现
(2)内点表示的四连通区域种子填充的实现
4、将上述算法作部分改动应用于八连通区域,构成八连通区域种子填充算法,
并编程实现。
三、实验结果分析
四连通图的实现:
程序代码:
#include<graphics.h>
#include <conio.h>
#include<math.h>
#include<time.h>
void BoundaryFill4(int x,int y,int Boundarycolor,int newcolor)
{
if(getpixel(x,y) != newcolor && getpixel(x,y) !=Boundarycolor)
{
putpixel(x,y,newcolor);
Sleep(1);
BoundaryFill4(x-1,y,Boundarycolor,newcolor);
BoundaryFill4(x,y+1,Boundarycolor,newcolor);
BoundaryFill4(x+1,y,Boundarycolor,newcolor);
BoundaryFill4(x,y-1,Boundarycolor,newcolor);
}
}
void polygon(int x0,int y0,int a,int n,float af)
{
int x,y,i;
double dtheta,theta;
if(n<3)
return;
dtheta=6.28318/n;
theta=af*0.0174533;
moveto(x0,y0);x=x0;y=y0;
for(i=1;i<n;i++)
{
x=x+a*cos(theta);y=y+a*sin(theta);
lineto(x,y);theta=theta+dtheta;
}
lineto(x0,y0);
}
void main()
{
int x=50,y=75;
int a,b,c,d,i,j;
int graphdriver=DETECT;
int graphmode=0;
initgraph(&graphdriver,&graphmode," ");
cleardevice();
setcolor(RGB(0,255,0));
setfillstyle(WHITE);
polygon(x,y,60,5,0.);
a=100;
b=100;
c=RGB(0,255,0);
d=RGB(255,0,255);
BoundaryFill4(a,b,c,d);
getch();
closegraph();}
实验结果
八连通的实现
程序代码:
#include<graphics.h>
#include<conio.h>
#include<time.h>
#include <malloc.h>
#include <windows.h>
#define MaxSize 100
typedef struct{
int x;
int y;
}Seed,ElemType;
typedef struct
{
ElemType data[MaxSize];
int top; //栈顶指针
} SqStack;
void InitStack(SqStack *&s)
{
s=(SqStack *)malloc(sizeof(SqStack));
s->top=-1;
}
int StackEmpty(SqStack *s)
{
return(s->top==-1);
}
int Push(SqStack *&s,ElemType e)
{
if (s->top==MaxSize-1)
return 0;
s->top++;
s->data[s->top]=e;
return 1;
}
int Pop(SqStack *&s,ElemType &e)
{
if (s->top==-1)
return 0;
e=s->data[s->top];
s->top--;
return 1;
}
void floodfill8(int x,int y,int oldcolor,int newcolor) {
if(getpixel(x,y)==oldcolor)
{
putpixel(x,y,newcolor);
Sleep(2);
floodfill8(x,y+1,oldcolor,newcolor);
floodfill8(x,y-1,oldcolor,newcolor);
floodfill8(x-1,y,oldcolor,newcolor);
floodfill8(x+1,y,oldcolor,newcolor);
floodfill8(x+1,y+1,oldcolor,newcolor);
floodfill8(x+1,y-1,oldcolor,newcolor);
floodfill8(x-1,y+1,oldcolor,newcolor);
floodfill8(x-1,y-1,oldcolor,newcolor);
}
}
void main()
{
int a,b,c,d,i,j;
int graphdriver=DETECT;
int graphmode=0;
initgraph(&graphdriver,&graphmode," "); cleardevice();
setfillstyle(RGB(255,255,255));
setcolor(GREEN);
int points[]={320,200,270,290,370,290}; fillpoly(3,points);
rectangle(500,420,100,100);
a=RGB(255,255,255);
b=RGB(255,0,0);
floodfill8(320,240,a,b);
c=RGB(0,0,0);
d=RGB(0,0,255);
floodfill8(320,180,c,d);
getch();
closegraph();
}
实验结果:
2、结果分析:
通过以上各算法运行结果分析与对比可知:
1.四连通算法的缺点是有时不能通过狭窄区域,因而不能填满多边形。
2.八连通算法的缺点是有时会填出多边形的边界。
3.由于填不满往往比涂出更易于补救,因此四连通算法比八连通算法用的更多。