簡體   English   中英

OpenGL glReadPixels 返回 0

[英]OpenGL glReadPixels returns 0

當我渲染到屏幕緩沖區時一切正常,但是當使用 glReadPixels 從 FrameBuffer 讀取像素時,它總是返回 0。

偽代碼如下:

將紋理綁定到 FrameBuffer:

GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
int width, height;
width = 2;
height = 2;
float texture_data[] = {
    1.0f, 0.0f, 0.0f,   1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,   1.0f, 0.0f, 0.0f
};
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_FLOAT, texture_data);
GLuint framebuffer;
glGenFramebuffers(1, &framebuffer); 
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); 
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); 
GLint texture_coord_attribute = glGetAttribLocation(program, "texture_coord");
glEnableVertexAttribArray(texture_coord_attribute);
glVertexAttribPointer(texture_coord_attribute, 2, GL_FLOAT, GL_FALSE,
    sizeof(vertices[0]), (void*)(sizeof(float) * 5));

片段/頂點着色器:

static const char* vertex_shader_text =
"#version 330\n""
"attribute vec2 vPos;\n"
"attribute vec2 texture_coord;\n"
"varying vec2 Texcoord;\n"
"void main()\n"
"{\n"
"    gl_Position = vec4(vPos, 0.0, 1.0);\n"
"    Texcoord = texture_coord;\n"
"}\n";

static const char* fragment_shader_text =
"#version 330\n"
"varying vec2 Texcoord;\n"
"uniform sampler2D tex;\n"
"void main()\n"
"{\n"
"    gl_FragColor = texture(tex, Texcoord);\n"
"}\n";

在主循環中讀取像素:

glViewport(0, 0, 720, 480);
glUseProgram(program);
glDrawArrays(GL_TRIANGLES, 0, 6);

GLubyte pixels[3] = {0};
glReadBuffer(GL_COLOR_ATTACHMENT0);
glReadPixels(360, 240, 1, 1, GL_RGB, GL_FLOAT, pixels);
// Any value returns 0 not only 360 and 240
printf("|%f||%f||%f|\n", pixels[0], pixels[1], pixels[2]);

glfwSwapBuffers(window);
glfwPollEvents();

這是我遵循的管道。 這里有什么問題? 謝謝。

glReadPixels的第 5 個和第 6 個參數( formattype )指定了目標像素數據的格式和數據類型。

由於您要讀取元素數據類型為GLubyte的緩沖區,因此類型必須為GL_BYTE

像這樣更改您的代碼:

glReadPixels(360, 240, 1, 1, GL_RGB, GL_BYTE, pixels);

或者將數據讀取到GLfloat類型的緩沖區:

GLfloat pixels[3];
glReadPixels(360, 240, 1, 1, GL_RGB, GL_FLOAT, pixels);


請注意,您所做的是將 12 個字節( sizeof(float)*3 )讀取到一個大小為 3 個字節( GLubyte pixels[3] )的緩沖區中。 這意味着代表紅色通道的浮點值的一部分被存儲到緩沖區中。 其余的會覆蓋一些訪問錯誤的內存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM