我一直在寻找一种将OpenGL纹理转换为OpenCV矩阵类型的方法。我找到了很多指南,展示了从OpenCV矩阵到OpenGL纹理的转换,但可悲的是没有反向转换的指南。我也阅读了this和它的answer,但并没有让我更聪明。我使用OpenCV3.1和OpenGL4.4编写C++代码。
编辑:更新的代码
编辑:更新的代码
main.cpp:
#include "CameraCapture.h"
#include "GUIMainWindow.h"
#include "glfw3.h"
#include "Texture.h"
using namespace std;
int main(int argc, char* argv[]) {
if (!glfwInit()) {
fprintf(stderr, "Failed to initialize GLFW \n");
return -1;
}
glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
GLFWwindow* window = glfwCreateWindow(1929, 1341, "OpenGL", NULL, NULL);
if (window == NULL) {
fprintf(stderr, "Failed to make GLFW window.");
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
CameraCapture *cc = new CameraCapture();
cc->CameraCapture::AvailableCameras();
GLuint texture = cc->CameraCapture::OpenCamera(0);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
drawGLTexture(window);
Mat out = textureToMat(texture);
namedWindow("Raytrix feed", WINDOW_AUTOSIZE);
imshow("Raytrix feed", out);
waitKey(0);
return 0;
}
Texture.cpp:
Mat textureToMat(GLuint texture_id) {
glBindTexture(GL_TEXTURE_2D, texture_id);
GLenum texture_width, texture_height;
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, (GLint*)&texture_width);
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, (GLint*)&texture_height);
unsigned char* texture_bytes = (unsigned char*)malloc(sizeof(unsigned char)*texture_width*texture_height * 4);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture_bytes);
return Mat(texture_height, texture_width, CV_8UC4, texture_bytes);
}
void drawGLTexture(GLFWwindow *window) {
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_TRIANGLES);
glTexCoord2f(0, 1);
glVertex2f(-1, -1);
glTexCoord2f(1, 1);
glVertex2f(1, -1);
glTexCoord2f(0, 0);
glVertex2f(-1, 1);
glTexCoord2f(1, 1);
glVertex2f(1, -1);
glTexCoord2f(1, 0);
glVertex2f(1, 1);
glTexCoord2f(0, 0);
glVertex2f(-1, 1);
glEnd();
glfwSwapBuffers(window);
glfwPollEvents();
glFlush();
glFinish();
}
头部:
#ifndef TEXTURE_H
#define TEXTURE_H
#include "glew.h"
#include "glfw3.h"
#include <string>
#include <iostream>
#include <vector>
#include <opencv\highgui.h>
#include <opencv\cv.h>
#include <opencv2\opencv.hpp>
using namespace std;
using namespace cv;
Mat textureToMat(GLuint textureID);
void drawGLTexture(GLFWwindow *window);
#endif /*!TEXTURE_H*/
glReadPixels
的用途。但这通常不涉及纹理。 - datenwolf