圖形填充之種子填充算法


編譯器: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 }

 

結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM