Hello,
I have written a program to render a triangulated 3D face model and save it as an image. My application also requires me to comoute the exact 3D coordinates and surface normals of the point which (by orthographic projection) produced every fore-ground pixel in the image. I have a way of throwing out pixels in the image that correspond to the background instead of the actual 3d face model (I know that the background pixels are colored (0,0,0)).
Now, I use glReadPixels to read the RGB values of the rendered 3D model and then store them in an image. The image is all fine. However when I try to use glReadPixels to obtain the depth values, I get garbage. Could someone help me with this? What could be going wrong? Here is a snippet of my code:
DrawModel(); // render a 3D model
glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
glGetDoublev(GL_PROJECTION_MATRIX,projMatrix);
glGetIntegerv(GL_VIEWPORT,viewport);
for (i=0;i<nr;i++)/nr=number of rows (in image)/
{
for (j=0;j<nc;j++)/nc=number of columns (in image)/
{
val = (RGB[(i+j*width)3] + RGB[(i+jwidth)3 +1]+RGB[(i+jwidth)*3 + 2])/3;
/* black pixels belong to the background, so ignore them. /
if ((int)val != 0)
{
/ read the depth value corresp. to pixel (j,nr-i-1) /
glReadPixels(j,nr-1-i,1,1,GL_DEPTH_COMPONENT,GL_FLOAT,&Z1);
/ get the coordinate of the point on the 3D model that produced this pixel */
if(gluUnProject(j,nr-1-i,Z1,modelMatrix,projMatrix,viewport,&objX,&objY,&objZ)== GL_TRUE) /*3D points stored in objX,objY,objZ */
{
Write (objX, objY, objZ) to a file.
} // close if loop
} // close for loop
} // close for loop
Here is the code to render the 3D model:
DrawModel
{
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0,0,width,height);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt (0cos(theta)+115sin(theta), 0.0, 0sin(theta)+115.0cos(theta), 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
glOrtho(-200,200,-200,200,300,-300);
glBegin(GL_TRIANGLES);
Render the triangular faces of the model, using normals for lighting.
glEnd();
RGB = (unsigned char *) malloc(width * height * sizeof(unsigned char) * 3);
/* buffer to store color values /
glReadPixels(0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,(void)RGB);
// Write to a pgm file.
glutSwapBuffers();
}