OpenCV4入门教程027:OpenGL纹理贴图

索引地址:系列索引

OpenGL在新手开发的时候可以配合glut/glfw等等使用,但是glut的官方网页上写着只适合测试和教程,如果需要性能就要使用其他的GUI。在Linux上面,最出名的GUI就是Qt了。

本文使用OpenCV的视频功能捕获视频数据,然后以OpenGL纹理贴图的方式显示。

函数原型:

1
2
3
4
void cv::setOpenGlDrawCallback( const String & winname, //窗口名
OpenGlDrawCallback onOpenGlDraw, //OpenGL回调函数
void * userdata = 0 //传递给回调函数的参数指针
);

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

// OpenGL includes
#ifdef __APPLE__
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif

// OpenCV includes
#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
using namespace cv;

Mat frame;
GLfloat angle = 0.0;
GLuint texture;
VideoCapture camera;

int loadTexture() {

if (frame.data == NULL)
return -1;

glBindTexture(GL_TEXTURE_2D, texture); // bind the texture to it's array
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, frame.cols, frame.rows, 0, GL_BGR, GL_UNSIGNED_BYTE,
frame.data);
return 0;
}

void on_opengl(void *param) {
glLoadIdentity();
// Load Texture
glBindTexture(GL_TEXTURE_2D, texture);
// Rotate plane
glRotatef(angle, 1.0f, 1.0f, 1.0f);
// Create the plate
glBegin(GL_QUADS);
glTexCoord2d(0.0, 0.0);
glVertex2d(-1.0, -1.0);
glTexCoord2d(1.0, 0.0);
glVertex2d(+1.0, -1.0);
glTexCoord2d(1.0, 1.0);
glVertex2d(+1.0, +1.0);
glTexCoord2d(0.0, 1.0);
glVertex2d(-1.0, +1.0);
glEnd();
}

int main(int argc, const char **argv) {
// Open WebCam
camera.open(0);
if (!camera.isOpened())
return -1;

// Create new windows
namedWindow("OpenGL Camera", WINDOW_OPENGL);

// Enable texture
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &texture);

setOpenGlDrawCallback("OpenGL Camera", on_opengl);

while (waitKey(30) != 'q') {
camera >> frame;
// Create first texture
loadTexture();
updateWindow("OpenGL Camera");
angle = angle + 4;
}

return 0;
}

测试效果:

opengl-opencv

具体OpenGL开发见OpenGL开发入门系列教程


OpenCV4入门教程027:OpenGL纹理贴图
https://feater.top/opencv/opencv-opengl-texture/
作者
JackeyLea
发布于
2020年11月10日
许可协议