如何将 moderngl fbo(帧缓冲区对象)读回 numpy 数组?

How do I read a moderngl fbo(frame buffer object) back into a numpy array?

我有两个 FBO 之一,我一直在使用它在 glsl 中进行一些计算,我需要将纹理数据(dtype='f4')读回一个 numpy 数组以进行进一步计算.我没有在说明如何执行此操作的文档中找到任何内容。有帮助吗?

我用这个创建纹理

self.texturePing = self.ctx.texture( (width, height), 4, dtype='f4')
self.texturePong = self.ctx.texture( (width, height), 4, dtype='f4')

我这样处理它们:

def render(self, time, frame_time):
        self.line_texture.use(0)
        self.transform['lineImg'].value = 0
        for _ in range (2):
            self.fbo2.use()
            self.texturePing.use(1)
            self.transform['prevData'].value = 1

            self.process_vao.render(moderngl.TRIANGLE_STRIP)

            #this rendered to texturePong 
            self.fbo1.use() #texture Ping


            self.texturePong.use(1)
            self.transform['prevData'].value = 1                
            self.process_vao.render(moderngl.TRIANGLE_STRIP)

        #stop drawing to the fbo and draw to the screen
        self.ctx.screen.use()
        self.ctx.clear(1.0, 1.0, 1.0, 0.0) #might be unnecessary   
        #tell the canvas to use this as the final texture 
        self.texturePing.use(3)
        self.canvas_prog['Texture'].value = 3
        #bind the ping texture as the Texture in the shader
        self.canvas_vao.render(moderngl.TRIANGLE_STRIP)

        # this looks good but how do I read texturePong back into a numpy array??

使用glGetTexImage(或者最好是glGetTextureImage)将数据复制到缓冲区(从您用于颜色数据的纹理)。

https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGetTexImage.xhtml

glGetTextureImage(textureToReadFrom, 0, GL_RGBA, GL_FLOAT, bufferSize, bufferPointer);

您可以使用 fbo.read 读取帧缓冲区的内容。

您可以使用 np.frombuffer

将缓冲区变成一个 numpy 数组

示例:

raw = self.fbo1.read(components=4, dtype='f4') # RGBA, floats
buf = np.frombuffer(raw, dtype='f4')