首页 > 代码库 > 图形填充之种子填充算法

图形填充之种子填充算法

编译器:VS2013

算法:在图形内选择一个点为种子,然后对这个种子四方位坐标未着色的入栈,出栈便着色,如此重复,等到栈内为空,则着色完成

代码:

 1 #include "stdafx.h"
 2 #include<stdio.h>
 3 #include"graphics.h"
 4 #include<stdlib.h>
 5 #include<stack>
 6 
 7 using namespace std;
 8 
 9 //定义结构体存储像素坐标
10 struct Point
11 {
12     int x;
13     int y;
14 };
15 
16 //函数声明
17 void Boundaryfilling(Point a[], int n);
18 void judgecolor(int x, int y, stack<int> &sx, stack<int> &sy);
19 
20 int main()
21 {
22     int gdriver = DETECT, gmode, n, i;
23 
24     printf("please input number of point:\n");
25     scanf_s("%d", &n);
26 
27     Point *p=(Point *)malloc(n*sizeof(Point));    //动态分配内存
28 
29     printf("please input point :\n");
30     for (i = 0; i < n; i++)
31         scanf_s("%d%d", &p[i].x, &p[i].y);
32 
33     initgraph(&gdriver, &gmode, "");
34 
35     setcolor(BLUE);
36     setbkcolor(BLACK);
37 
38     //画出多边形
39     for (i = 0; i < n-1; i++)
40         line(p[i].x, p[i].y, p[i + 1].x, p[i + 1].y);
41 
42     Boundaryfilling(p, n);
43 
44     system("pause");
45     closegraph();
46 
47     return 0;
48 }
49 
50 void Boundaryfilling(Point a[], int n)
51 {
52     stack<int> sx,sy;
53     int x=0 , y=0 ,x0,y0,i;
54 
55     for (i = 0; i < n; i++)
56     {
57         x += a[i].x;
58         y += a[i].y;
59     }
60 
61     x = x / (n-1);
62     y = y / (n-1);
63 
64     sx.push(x);//x坐标入栈
65     sy.push(y);//y坐标入栈
66 
67     while (!sx.empty())    //判断栈是否为空
68     {
69         x0 = sx.top();
70         y0 = sy.top();
71 
72         putpixel(sx.top(), sy.top(), YELLOW);    //栈顶元素着色
73         sx.pop();//栈顶元素出栈
74         sy.pop();//栈顶元素出栈
75 
76         judgecolor(x0 - 1, y0, sx, sy);//左边点
77         judgecolor(x0 + 1, y0, sx, sy);//右边点
78         judgecolor(x0, y0 - 1, sx, sy);//下边点
79         judgecolor(x0, y0 + 1, sx, sy);//上边点
80     }
81 }
82 
83 //判断该像素是否没有着色
84 void judgecolor(int x, int y,stack<int> &sx,stack<int> &sy)
85 {
86     if (getpixel(x, y) == BLACK)
87     {
88         sx.push(x);
89         sy.push(y);
90     }
91 }

 

结果:

技术分享

图形填充之种子填充算法