生成QT opengl 显示 yuv的代码
时间: 2023-05-27 14:07:17 浏览: 76
下面是一个简单的QT OpenGL显示YUV图像的示例代码:
```c++
#include <QtOpenGL/QGLWidget>
#include <QImage>
#include <QKeyEvent>
class YUVWidget : public QGLWidget
{
Q_OBJECT
public:
YUVWidget(QWidget *parent = nullptr);
protected:
void initializeGL();
void paintGL();
void resizeGL(int w, int h);
void keyPressEvent(QKeyEvent *event);
private:
GLuint m_textureY;
GLuint m_textureU;
GLuint m_textureV;
int m_width;
int m_height;
bool m_showY;
bool m_showU;
bool m_showV;
};
YUVWidget::YUVWidget(QWidget *parent) : QGLWidget(parent)
{
m_textureY = 0;
m_textureU = 0;
m_textureV = 0;
m_width = 0;
m_height = 0;
m_showY = true;
m_showU = true;
m_showV = true;
}
void YUVWidget::initializeGL()
{
glEnable(GL_TEXTURE_2D);
glShadeModel(GL_FLAT);
glGenTextures(1, &m_textureY);
glGenTextures(1, &m_textureU);
glGenTextures(1, &m_textureV);
}
void YUVWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (m_width > 0 && m_height > 0)
{
int halfWidth = m_width / 2;
int halfHeight = m_height / 2;
// 绑定纹理Y
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_textureY);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_width, m_height, GL_RED, GL_UNSIGNED_BYTE, yData);
// 绑定纹理U
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_textureU);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, halfWidth, halfHeight, GL_RED, GL_UNSIGNED_BYTE, uData);
// 绑定纹理V
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, m_textureV);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, halfWidth, halfHeight, GL_RED, GL_UNSIGNED_BYTE, vData);
// 绘制图像
glBegin(GL_QUADS);
if (m_showY)
{
glTexCoord2f(0.0, 0.0);
glVertex3f(-1.0, -1.0, 0.0);
glTexCoord2f(1.0, 0.0);
glVertex3f(0.0, -1.0, 0.0);
glTexCoord2f(1.0, 1.0);
glVertex3f(0.0, 0.0, 0.0);
glTexCoord2f(0.0, 1.0);
glVertex3f(-1.0, 0.0, 0.0);
}
if (m_showU)
{
glTexCoord2f(0.0, 0.0);
glVertex3f(0.0, -1.0, 0.0);
glTexCoord2f(1.0, 0.0);
glVertex3f(1.0, -1.0, 0.0);
glTexCoord2f(1.0, 1.0);
glVertex3f(1.0, 0.0, 0.0);
glTexCoord2f(0.0, 1.0);
glVertex3f(0.0, 0.0, 0.0);
}
if (m_showV)
{
glTexCoord2f(0.0, 0.0);
glVertex3f(-1.0, 0.0, 0.0);
glTexCoord2f(1.0, 0.0);
glVertex3f(0.0, 0.0, 0.0);
glTexCoord2f(1.0, 1.0);
glVertex3f(0.0, 1.0, 0.0);
glTexCoord2f(0.0, 1.0);
glVertex3f(-1.0, 1.0, 0.0);
}
glEnd();
}
}
void YUVWidget::resizeGL(int w, int h)
{
glViewport(0, 0, w, h);
}
void YUVWidget::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Y)
{
m_showY = !m_showY;
update();
}
else if (event->key() == Qt::Key_U)
{
m_showU = !m_showU;
update();
}
else if (event->key() == Qt::Key_V)
{
m_showV = !m_showV;
update();
}
}
// 使用方法:
// 1. 创建YUVWidget对象
// 2. 在需要更新图像时,设置yData、uData、vData为图像数据,调用update()更新视图
```
在上述代码中,我们使用了OpenGL来绘制图像。我们需要创建三个纹理对象,分别用于存储Y、U、V分量的数据。在paintGL()函数中,我们首先绑定这三个纹理对象,并将图像数据传递给它们。然后,我们使用glBegin(GL_QUADS)和glVertex3f()函数来绘制图像。我们可以通过按下键盘上的Y、U、V键来切换是否显示对应的分量。