用python写一个OpenGL Widget显示图片得代码
时间: 2024-02-05 17:04:33 浏览: 173
openGL3D显示类
可以使用PyOpenGL和PyQt来实现一个OpenGL Widget显示图片的代码,以下是一个简单的示例代码:
```python
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QImage, QOpenGLShader, QOpenGLShaderProgram, QOpenGLTexture
from PyQt5.QtWidgets import QApplication, QOpenGLWidget
from OpenGL.GL import *
class OpenGLWidget(QOpenGLWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.texture = None
def initializeGL(self):
glClearColor(0.0, 0.0, 0.0, 1.0)
glEnable(GL_TEXTURE_2D)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
vertex_shader = QOpenGLShader(QOpenGLShader.Vertex)
vertex_shader.compileSourceCode("""
attribute vec2 position;
attribute vec2 tex_coord;
varying vec2 v_tex_coord;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
v_tex_coord = tex_coord;
}
""")
fragment_shader = QOpenGLShader(QOpenGLShader.Fragment)
fragment_shader.compileSourceCode("""
varying vec2 v_tex_coord;
uniform sampler2D tex;
void main() {
gl_FragColor = texture2D(tex, v_tex_coord);
}
""")
self.shader_program = QOpenGLShaderProgram()
self.shader_program.addShader(vertex_shader)
self.shader_program.addShader(fragment_shader)
self.shader_program.link()
self.shader_program.bind()
self.shader_program.enableAttributeArray("position")
self.shader_program.enableAttributeArray("tex_coord")
self.shader_program.setAttributeArray("position", GL_FLOAT, QtCore.QPointF(0, 0))
self.shader_program.setAttributeArray("tex_coord", GL_FLOAT, QtCore.QPointF(0, 1))
self.shader_program.release()
def paintGL(self):
glClear(GL_COLOR_BUFFER_BIT)
if self.texture is not None:
self.shader_program.bind()
self.texture.bind()
# Draw a rectangle that fills the entire widget
glBegin(GL_QUADS)
glTexCoord2f(0.0, 0.0)
glVertex2f(-1.0, -1.0)
glTexCoord2f(1.0, 0.0)
glVertex2f(1.0, -1.0)
glTexCoord2f(1.0, 1.0)
glVertex2f(1.0, 1.0)
glTexCoord2f(0.0, 1.0)
glVertex2f(-1.0, 1.0)
glEnd()
self.texture.release()
self.shader_program.release()
def resizeGL(self, width, height):
glViewport(0, 0, width, height)
def set_image(self, image):
if image is not None:
q_image = QImage(image.data, image.width, image.height, QImage.Format_RGB888)
self.texture = QOpenGLTexture(q_image)
self.update()
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
widget = OpenGLWidget()
widget.show()
sys.exit(app.exec_())
```
这个代码会创建一个继承自QOpenGLWidget的OpenGLWidget类,其中包含了一个显示图片的set_image方法。在initializeGL方法中,我们会编译一个顶点着色器和一个片段着色器,并将它们链接成一个ShaderProgram。在paintGL方法中,我们会绑定这个ShaderProgram,并将显示图片的纹理绑定到GL_TEXTURE_2D上,然后绘制一个填充整个widget的矩形。在set_image方法中,我们会将传入的图片转换成QImage格式,并创建一个QOpenGLTexture对象,然后调用update方法刷新OpenGLWidget。
阅读全文