首页 > 编程语言 > 详细

图形填充之种子填充算法

时间:2017-05-24 00:11:37      阅读:522      评论:0      收藏:0      [点我收藏+]

编译器: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 }

 

结果:

技术分享

图形填充之种子填充算法

原文:http://www.cnblogs.com/cdp1591652208/p/6896718.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!