当前位置:主页 > 软件编程 > C代码 >

OpenGL实现边缘填充算法

时间:2021-07-10 09:33:20 | 栏目:C代码 | 点击:

边缘填充的思想:枚举每一条边,对这条边右边的像素进行求补操作,就是有填充则去掉,无填充就进行填充

#include <GL/gl.h>
#include <GL/glut.h>
#include <iostream>
#include <cmath>
#include <cstring>
#include <string>
using namespace std;
int x[]= {10,70,70,60,40,30,20};
int y[]= {10,10,50,40,60,20,30};
int vis[500][500]; //判断该坐标的点是否存在
void init()
{
 glClearColor (0.0, 0.0, 0.0, 0.0);
 glMatrixMode (GL_PROJECTION);
 gluOrtho2D (0.0, 200.0, 0.0, 150.0);
}
void MidBresenhamCircle()
{
 memset(vis,0,sizeof(vis));
 glClear(GL_COLOR_BUFFER_BIT);
 glLineWidth(2);
 glBegin(GL_LINES); //绘制多边形形状
 for(int i=0; i<7; ++i)
 {
  glVertex2i(x[i],y[i]);
  glVertex2i(x[(i+1)%7],y[(i+1)%7]);
 }
 glEnd();
 glFlush();
 glPointSize(2);
 glBegin(GL_POINTS);
 for(int i=x[1],j=y[1]; i<300; ++i) //特殊处理k=0的边
 {
  if(!vis[i][j])
  {
   glColor3f(0.0f,1.0f,0.0f);
   glVertex2i(i,j);
   vis[i][j]=1;
  }
  else
  {
   glColor3f(0.0f,0.0f,0.0f);
   glVertex2i(i,j);
   vis[i][j]=1;
  }
 }
 for(int j=y[1]; j<=y[2]; ++j) //特殊处理k不存在的边
 {
  for(int i=x[1]; i<300; ++i)
  {
   if(!vis[i][j])
   {
    glColor3f(0.0f,1.0f,0.0f);
    glVertex2i(i,j);
    vis[i][j]=1;
   }
   else
   {
    glColor3f(0.0f,0.0f,0.0f);
    glVertex2i(i,j);
    vis[i][j]=1;
   }
  }
 }
 for(int p=2; p<7; ++p)
 {
  int k=(y[(p+1)%7]-y[p])/(x[(p+1)%7]-x[p]); //求出斜率
  int x1=x[(p+1)%7],x0=x[p],y1=y[(p+1)%7],y0=y[p]; //根据斜率推导出这条直线的各个点
  if(y1<y0)
  {
   swap(x1,x0);
   swap(y1,y0);
  }
  for(int j=y0; j<=y1; ++j)
  {
   int i=(j-y0+k*x0)/k;
   for(int px=i; px<300; ++px)
   {
    if(!vis[px][j])
    {
     glColor3f(0.0f,1.0f,0.0f);
     glVertex2i(px,j);
     vis[px][j]=1;
    }
    else
    {
     glColor3f(0.0f,0.0f,0.0f);
     glVertex2i(px,j);
     vis[px][j]=0;
    }
   }
  }
 }
 glEnd();
 glFlush();
}
int main(int argc, char *argv[])
{
 glutInit(&argc, argv);
 glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
 glutInitWindowPosition(100, 100);
 glutInitWindowSize(500, 500);
 glutCreateWindow("第一个opengl程序");
 init();
 glutDisplayFunc(MidBresenhamCircle);
 glutMainLoop();
 return 0;
}

效果

您可能感兴趣的文章:

相关文章