我正在尝试实现洪水填充算法。但是 glReadPixels() 返回的像素的浮点 RGB 值与我设置的实际值略有不同,导致算法失败。为什么会这样?
输出返回的 RGB 值进行检查。
#include<iostream>
#include<GL/glut.h>
using namespace std;
float boundaryColor[3]={0,0,0}, interiorColor[3]={0,0,0.5}, fillColor[3]={1,0,0};
float readPixel[3];
void init(void) {
glClearColor(0,0,0.5,0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0,500,0,500);
}
void setPixel(int x,int y) {
glColor3fv(fillColor);
glBegin(GL_POINTS);
glVertex2f(x,y);
glEnd();
}
void getPixel(int x, int y, float *color) {
glReadPixels(x,y,1,1,GL_RGB,GL_FLOAT,color);
}
void floodFill(int x,int y) {
getPixel(x,y,readPixel);
//outputting values here to check
cout<<readPixel[0]<<endl;
cout<<readPixel[1]<<endl;
cout<<readPixel[2]<<endl;
if( readPixel[0]==interiorColor[0] && readPixel[1]==interiorColor[1] && readPixel[2]==interiorColor[2] ) {
setPixel(x,y);
floodFill(x+1,y);
floodFill(x,y+1);
floodFill(x-1,y);
floodFill(x,y-1);
}
}
void display() {
glClear(GL_COLOR_BUFFER_BIT);
glColor3fv(boundaryColor);
glLineWidth(3);
glBegin(GL_LINE_STRIP);
glVertex2i(150,150);
glVertex2i(150,350);
glVertex2i(350,350);
glVertex2i(350,150);
glVertex2i(150,150);
glEnd();
floodFill(200,200);
glFlush();
}
int main(int argc,char** argv) {
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(100,100);
glutInitWindowSize(500,500);
glutCreateWindow("Flood fill");
init();
glutDisplayFunc(display);
glutMainLoop();
}