I've got code for flood fill algorithm.
void floodFill() {
float target[3] = { 1.0, 1.0, 0.0 };
float border[3] = { 1.0, 1.0, 1.0 };
float clearp[3] = { 0.0, 0.0, 0.0 };
std::stack<pixel*> colored;
if (!stack.empty()) // stack contains first pixel
colored.push(stack.top());
while(!colored.empty()) {
pixel *p = colored.top();
drawPixel(p->x, p->y, target);
colored.pop();
//up
float pix[3];
glReadPixels(p->x, p->y + KOEF, 1, 1, GL_RGB, GL_FLOAT, pix);
if (!compare(pix,border) && compare(pix,clearp)) {
pixel *pn = new pixel();
pn->x = p->x;
pn->y = p->y + KOEF;
colored.push(pn);
}
//down
glReadPixels(p->x, p->y - KOEF, 1, 1, GL_RGB, GL_FLOAT, pix);
if (!compare(pix,border) && compare(pix,clearp)) {
pixel *pn = new pixel();
pn->x = p->x;
pn->y = p->y - KOEF;
colored.push(pn);
}
//left
glReadPixels(p->x - KOEF, p->y, 1, 1, GL_RGB, GL_FLOAT, pix);
if (!compare(pix,border) && compare(pix,clearp)) {
pixel *pn = new pixel();
pn->x = p->x - KOEF;
pn->y = p->y;
colored.push(pn);
}
//right
glReadPixels(p->x + KOEF, p->y, 1, 1, GL_RGB, GL_FLOAT, pix);
if (!compare(pix,border) && compare(pix,clearp)) {
pixel *pn = new pixel();
pn->x = p->x + KOEF;
pn->y = p->y;
colored.push(pn);
}
}
}
I draw pixel using this method
void drawPixel(float x, float y, float *t) {
glRasterPos2i(x, y);
glDrawPixels(1, 1, GL_RGB, GL_FLOAT, t);
for(int i = 0; i < KOEF; i++) {
glRasterPos2i(x, y + i);
glDrawPixels(1, 1, GL_RGB, GL_FLOAT, t);
glRasterPos2i(x + i, y);
glDrawPixels(1, 1, GL_RGB, GL_FLOAT, t);
glRasterPos2i(x + i, y + i);
glDrawPixels(1, 1, GL_RGB, GL_FLOAT, t);
}
};
To fill some area I choose first pixel with mouse click and then call method floodFill.
void mouse(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
pixel *p = new pixel();
p->x = x;
p->y = HEIGHT - y;
if (!stack.empty())
stack.pop();
stack.push(p); // first pixel
floodFill();
}
};
The result is (for example)
But it works very slow(several seconds. area on the picture - it was drawing it for 11 seconds. area around letter - 43 seconds). And I thought it slowly will draw pixel after pixel but it is waiting for several seconds and then I see the result.
my pc is
intel core 2 duo p8600 2.4 GHz
nvidia 9600m gt 512 mb
windows x86
ram 4 GB(3)`
Should it work so slow or there is a problem?
That's a terrible way to use OpenGL.
Do your flood-fill in host memory, upload the resulting bitmap to an OpenGL texture, and then render a quad with that texture.
Should it work so slow or there is a problem?
No, it should not. Because Photoshop can make it faster :-)
It looks like there are some efficiency-related issues.
You should not use OpenGL calls for single pixel operations. You should better make a buffered copy of the image, process (floodfill) it, then copy back.
Why are you using these strange float coordinates instead of normal integer pixel indices?
And what about not using floats for colors too? Floating point operations are slower than integer ones and float values needs further convesion to internal image format.
Your program seems to be too OOP-ish for its purpose. It is not good idea to use new and stack in the innermost loop of the image processing routine.
Related
I'm trying to implement the flood fill algorithm in OpenGL, but I'm encountering an error doing so. The error is that the algorithm does not stop at the boundary, and simply keeps going until the edge of the window, and eventually crashes with a bad memory access error. I'm working on MacOS Mojave 10.14.4.
I think my implementation's logic is correct, however, I've printed out the color of each pixel from getPixel, and it is always white (the background color), even when getting the color of boundary pixels.
The code below draws a circle using Bresenham's Line algorithm (midpoint algorithm), and then flood fills it (unsuccessfully).
#include <GLUT/GLUT.h>
#include <iostream>
struct Color {
GLubyte r;
GLubyte g;
GLubyte b;
};
Color getPixelColor(GLint x, GLint y) {
Color color;
glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &color);
return color;
}
void setPixel (GLint x, GLint y) {
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
Color color = getPixelColor(x, y);
}
void setPixelColor(GLint x, GLint y, Color color) {
glColor3ub(color.r, color.g, color.b);
setPixel(x, y);
glEnd();
glFlush();
}
void floodFill4 (GLint x, GLint y, Color fillColor, Color interiorColor) {
Color color = getPixelColor(x, y);
if (color.r == interiorColor.r && color.g == interiorColor.g &&
color.b == interiorColor.b) {
setPixelColor(x, y, fillColor);
floodFill4 (x + 1, y, fillColor, interiorColor);
floodFill4 (x - 1, y, fillColor, interiorColor);
floodFill4 (x, y + 1, fillColor, interiorColor);
floodFill4 (x, y - 1, fillColor, interiorColor);
}
}
void drawCirclePoint(GLint x, GLint y, GLint cx, GLint cy) {
setPixel(cx+x, cy+y);
setPixel(cx+y, cy+x);
setPixel(cx-y, cy+x);
setPixel(cx-x, cy+y);
setPixel(cx-x, cy-y);
setPixel(cx-y, cy-x);
setPixel(cx+y, cy-x);
setPixel(cx+x, cy-y);
}
void drawCircle(GLint cx, GLint cy, GLint radius) {
int p = 1 - radius;
GLint x = 0;
GLint y = radius;
while (x < y) {
drawCirclePoint(x, y, cx, cy);
if (p < 0) {
x++;
p += (2 * x) + 1;
} else {
x++;
y--;
p += (2 * x) + 1 - (2 * y);
}
}
}
void displayMe(void) {
glClear(GL_COLOR_BUFFER_BIT);
glColor3ub(0, 0, 0);
GLint cx = 0;
GLint cy = 0;
GLint radius = 200;
// Draw head
glColor3ub(0, 0, 0);
drawCircle(cx, cy, radius);
glEnd();
glFlush();
Color interiorColor = {255, 255, 255};
Color fillColor = {0, 0, 255};
// floodFill4(100, 100, fillColor, interiorColor);
}
void init (void) {
glClearColor(1.0, 1.0, 1.0, 0.0); // Set display-window color to white.
glMatrixMode(GL_PROJECTION); // Set projection parameters.
glLoadIdentity();
gluOrtho2D(-1000.0, 1000.0, -1000.0, 1000.0);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(1000, 1000);
glutInitWindowPosition(100, 100);
glutCreateWindow("My Drawing");
init();
glutDisplayFunc(displayMe);
glutMainLoop();
return 0;
}
I've looked at this post, which seems similar, but wasn't able to find a solution.
If you're going to persist with glVertex() for point plotting make sure you set up your matrix stack transforms (GL_PROJECTION/GL_MODELVIEW) so they match the glReadPixels() coordinate system:
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0, glutGet(GLUT_WINDOW_WIDTH), 0, glutGet(GLUT_WINDOW_HEIGHT) );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
Or switch to glRasterPos() + glDrawPixels() for setPixel*().
Better yet, do the flood-fill logic host-side & upload the results to a GL texture for display.
Either way you're going to run into a stack overflow with that recursive solution on even fairly reasonably sized inputs so you'll probably want to switch to an explicit stack/queue:
void floodFill4( GLint aX, GLint aY, Color fillColor, Color interiorColor )
{
typedef std::pair< GLint, GLint > Location;
std::queue< Location > locations;
locations.push( Location( aX, aY ) );
while( !locations.empty() )
{
const Location loc = locations.front();
locations.pop();
GLint x = loc.first;
GLint y = loc.second;
Color color = getPixelColor( x, y );
if( color.r == interiorColor.r &&
color.g == interiorColor.g &&
color.b == interiorColor.b )
{
setPixelColor( x, y, fillColor );
locations.push( Location( x, y - 1 ) );
locations.push( Location( x, y + 1 ) );
locations.push( Location( x - 1, y ) );
locations.push( Location( x + 1, y ) );
}
}
}
I am using vertex arrays to store circle vertices and colors.
Here is the setup function:
void setup1(void)
{
glClearColor(1.0, 1.0, 1.0, 0.0);
// Enable two vertex arrays: co-ordinates and color.
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
// Specify locations for the co-ordinates and color arrays.
glVertexPointer(3, GL_FLOAT, 0, Vertices1);
glColorPointer(3, GL_FLOAT, 0, Colors1);
}
The global declaration of the arrays is here:
static float Vertices1[500] = { 0 };
static float Colors1[500] = { 0 };
The arrays are all set up here (R is the radius, X and Y are the (X,Y) center, and t is the angle parameter of the circle)
void doGlobals1()
{
for (int i = 0; i < numVertices1 * 3; i += 3)
{
Vertices1[i] = X + R * cos(t);
Vertices1[i + 1] = Y + R * sin(t);
Vertices1[i + 2] = 0.0;
t += 2 * PI / numVertices1;
}
for (int j = 0; j < numVertices1 * 3; j += 3)
{
Colors1[j] = (float)rand() / (float)RAND_MAX;
Colors1[j + 1] = (float)rand() / (float)RAND_MAX;
Colors1[j + 2] = (float)rand() / (float)RAND_MAX;
}
}
Finally, this is where the shape is drawn.
// Window 1 drawing routine.
void drawScene1(void)
{
glutSetWindow(win1);
glLoadIdentity();
doGlobals1();
glClear(GL_COLOR_BUFFER_BIT);
glRotatef(15, 1, 0, 0);
glDrawArrays(GL_TRIANGLE_FAN, 0, numVertices1);
glFlush();
}
Without the Rotation, the circle draws just fine. The circle also draws fine with any Scale/Translate function. I suspect there is some special protocol necessary to rotate an object drawn with vertex arrays.
Can anyone tell me where I have gone wrong, what I will need to do in order to rotate the object, or offer any advice?
glRotatef(15, 1, 0, 0);
^ why the X axis?
The default ortho projection matrix has pretty tight near/far clipping planes: -1 to 1.
Rotating your circle of X/Y coordinates outside of the X/Y plane will tend to make those points get clipped.
Rotate around the Z axis instead:
glRotatef(15, 0, 0, 1);
So I have this piece of code, which pretty much draws various 2D textures on the screen, though there are multiple sprites that have to be 'dissected' from the texture (spritesheet). The problem is that rotation is not working properly; while it rotates, it does not rotate on the center of the texture, which is what I am trying to do. I have narrowed it down to the translation being incorrect:
glTranslatef(x + sr->x/2 - sr->w/2,
y + sr->y/2 - sr->h/2,0);
glRotatef(ang,0,0,1.f);
glTranslatef(-x + -sr->x/2 - -sr->w/2,
-y + -sr->y/2 - -sr->h/2,0);
X and Y is the position that it's being drawn to, the sheet rect struct contains the position X and Y of the sprite being drawn from the texture, along with w and h, which are the width and heights of the 'sprite' from the texture. I've tried various other formulas, such as:
glTranslatef(x, y, 0);
The below three switching the negative sign to positive (x - y to x + y)
glTranslatef(sr->x/2 - sr->w/2, sr->y/2 - sr->h/2 0 );
glTranslatef(sr->x - sr->w/2, sr->y - sr->h/2, 0 );
glTranslatef(sr->x - sr->w, sr->y - sr->w, 0 );
glTranslatef(.5,.5,0);
It might also be helpful to say that:
glOrtho(0,screen_width,screen_height,0,-2,10);
is in use.
I've tried reading various tutorials, going through various forums, asking various people, but there doesn't seem to be a solution that works, nor can I find any useful resources that explain to me how I find the center of the image in order to translate it to '(0,0)'. I'm pretty new to OpenGL so a lot of this stuff takes awhile for me to digest.
Here's the entire function:
void Apply_Surface( float x, float y, Sheet_Container* source, Sheet_Rect* sr , float ang = 0, bool flipx = 0, bool flipy = 0, int e_x = -1, int e_y = -1 ) {
float imgwi,imghi;
glLoadIdentity();
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,source->rt());
// rotation
imghi = source->rh();
imgwi = source->rw();
Sheet_Rect t_shtrct(0,0,imgwi,imghi);
if ( sr == NULL ) // in case a sheet rect is not provided, assume it's width
//and height of texture with 0/0 x/y
sr = &t_shtrct;
glPushMatrix();
//
int wid, hei;
glGetTexLevelParameteriv(GL_TEXTURE_2D,0,GL_TEXTURE_WIDTH,&wid);
glGetTexLevelParameteriv(GL_TEXTURE_2D,0,GL_TEXTURE_HEIGHT,&hei);
glTranslatef(-sr->x + -sr->w,
-sr->y + -sr->h,0);
glRotatef(ang,0,0,1.f);
glTranslatef(sr->x + sr->w,
sr->y + sr->h,0);
// Yeah, out-dated way of drawing to the screen but it works for now.
GLfloat tex[] = {
(sr->x+sr->w * flipx) /imgwi, 1 - (sr->y+sr->h *!flipy )/imghi,
(sr->x+sr->w * flipx) /imgwi, 1 - (sr->y+sr->h * flipy)/imghi,
(sr->x+sr->w * !flipx) /imgwi, 1 - (sr->y+sr->h * flipy)/imghi,
(sr->x+sr->w * !flipx) /imgwi, 1 - (sr->y+sr->h *!flipy)/imghi
};
GLfloat vertices[] = { // vertices to put on screen
x, (y + sr->h),
x, y,
(x +sr->w), y,
(x +sr->w),(y +sr->h)
};
// index array
GLubyte index[6] = { 0,1,2, 2,3,0 };
float fx = (x/(float)screen_width)-(float)sr->w/2/(float)imgwi;
float fy = (y/(float)screen_height)-(float)sr->h/2/(float)imghi;
// activate arrays
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
// pass verteices and texture information
glVertexPointer(2, GL_FLOAT, 0, vertices);
glTexCoordPointer(2, GL_FLOAT, 0, tex);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, index);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
}
Sheet container class:
class Sheet_Container {
GLuint texture;
int width, height;
public:
Sheet_Container();
Sheet_Container(GLuint, int = -1,int = -1);
void Load(GLuint,int = -1,int = -1);
float rw();
float rh();
GLuint rt();
};
Sheet rect class:
struct Sheet_Rect {
float x, y, w, h;
Sheet_Rect();
Sheet_Rect(int xx,int yy,int ww,int hh);
};
Image loading function:
Sheet_Container Game_Info::Load_Image(const char* fil) {
ILuint t_id;
ilGenImages(1, &t_id);
ilBindImage(t_id);
ilLoadImage(const_cast<char*>(fil));
int width = ilGetInteger(IL_IMAGE_WIDTH), height = ilGetInteger(IL_IMAGE_HEIGHT);
return Sheet_Container(ilutGLLoadImage(const_cast<char*>(fil)),width,height);
}
Your quad (two triangles) is centered at:
( x + sr->w / 2, y + sr->h / 2 )
You need to move that point to the origin, rotate, and then move it back:
glTranslatef ( (x + sr->w / 2.0f), (y + sr->h / 2.0f), 0.0f); // 3rd
glRotatef (0,0,0,1.f); // 2nd
glTranslatef (-(x + sr->w / 2.0f), -(y + sr->h / 2.0f), 0.0f); // 1st
Here is where I think you are getting tripped up. People naturally assume that OpenGL applies transformations in the order they appear (top-to-bottom), that is not the case. OpenGL effectively swaps the operands everytime it multiplies two matrices:
M1 x M2 x M3
~~~~~~~
(1)
~~~~~~~~~~
(2)
(1) M2 * M1
(2) M3 * (M2 * M1) --> M3 * M2 * M1 (row-major / textbook math notation)
The technical term for this is post-multiplication, it all has to do with the way matrices are implemented in OpenGL (column-major). Suffice it to say, you should generally read glTranslatef, glRotatef, glScalef, etc. calls from bottom-to-top.
With that out of the way, your current rotation does not make any sense.
You are telling GL to rotate 0 degrees around an axis: <0,0,1> (the z-axis in other words). The axis is correct, but a 0 degree rotation is not going to do anything ;)
I'm trying to get data from pixel using glReadPixels.
It was working for some time. But now it stopped working and I don't know why.
I need to make Flood fill algorithm.
glBegin(GL_POINTS);
float target[3] = { 1.0, 1.0, 0.0 }; // target color
float border[3] = { 1.0, 1.0, 1.0 }; // border color
float clearp[3] = { 0.0, 0.0, 0.0 }; // clear color
std::stack<pixel*> colored; // stack with pixels
if (!stack.empty()) // stack contains first pixel
colored.push(stack.top());
while(!colored.empty()) {
pixel *p = colored.top();
glRasterPos2i(p->x, p->y);
glDrawPixels(1, 1, GL_RGB, GL_FLOAT, target);
colored.pop();
//up
float pix[3];
glReadPixels(p->x, p->y + 1, 1, 1, GL_RGB, GL_FLOAT, pix);
if (!compare(pix,border) && compare(pix,clearp)) {
pixel *pn = new pixel();
pn->x = p->x;
pn->y = p->y + 1;
colored.push(pn);
}
//down
glReadPixels(p->x, p->y - 1, 1, 1, GL_RGB, GL_FLOAT, pix);
if (!compare(pix,border) && compare(pix,clearp)) {
pixel *pn = new pixel();
pn->x = p->x;
pn->y = p->y - 1;
colored.push(pn);
}
//left
glReadPixels(p->x - 1, p->y, 1, 1, GL_RGB, GL_FLOAT, pix);
if (!compare(pix,border) && compare(pix,clearp)) {
pixel *pn = new pixel();
pn->x = p->x - 1;
pn->y = p->y;
colored.push(pn);
}
//right
glReadPixels(p->x + 1, p->y, 1, 1, GL_RGB, GL_FLOAT, pix);
if (!compare(pix,border) && compare(pix,clearp)) {
pixel *pn = new pixel();
pn->x = p->x + 1;
pn->y = p->y;
colored.push(pn);
}
}
glEnd();
But array pix does not contain RGB color data. It usually something like this -1.0737418e+008
Where is the problem? It should work fine...
It's an error to call anything but a very limited set of functions between glBegin and glEnd. That list is mostly composed of functions related to specifying attributes of a vertex (e.g., glVertex, glNormal, glColor, glTexCoord, etc.).
So, if your OpenGL implementation is following the OpenGL specification, glReadPixels should return immediately without executing because of being called within a glBegin/glEnd group. Remove those from around your calls, and glReadPixels should work as expected.
I need to set color for pixel.
When I try to set color of a certain pixel(by clicking left mouse button). My mouse function.
void mouse(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
pixel *p = new pixel();
p->x = x;
p->y = HEIGHT - y;
stack.push(p);
float arr[3];
readPixel(p->x, p->y, arr);
std::cout<<"pixel color: ";
std::cout<<arr[0]<<" "<<arr[1]<<" "<<arr[2]<<std::endl;
drawPixel(p->x, p->y);
}
}
Here readPixel method
void readPixel(int x, int y, float (&a)[3]) {
GLubyte arr[3];
glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, arr);
a[0] = (float)arr[0] / 255.0f;
a[1] = (float)arr[1] / 255.0f;
a[2] = (float)arr[2] / 255.0f;
};
The problem is with setting color for pixel.
I create structure pixel with fields x and y. When I click left button, object pixel is added to stack.
When I try to set color for pixel(draw it) - pixel does not change its color in method drawPixel
void draw() {
glBegin(GL_POINTS);
if (!stack.empty()) {
drawPixel(stack.top()->x, stack.top()->y);
stack.pop();
}
glEnd();
glFlush();
};
void drawPixel(int x, int y) {
glRasterPos2i(x, y);
glDrawPixels(1, 1, GL_RGB, GL_UNSIGNED_BYTE, &val);
};
Where &val is float val[3] = { 1.0, 1.0, 0.0 };
So the question is how to set color for pixel with coordinates x and y?
The solution is to change GL_UNSIGNED_BYTE to GL_FLOAT and not pop items from stack