opengl.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. #include <iostream>
  2. #ifdef _WIN32
  3. #define WIN32_LEAN_AND_MEAN 1
  4. #define NOMINMAX 1
  5. #include <windows.h>
  6. #endif
  7. #if defined(__APPLE__)
  8. #include <OpenGL/gl.h>
  9. #include <OpenGL/glu.h>
  10. #else
  11. #include <GL/gl.h>
  12. #include <GL/glu.h>
  13. #endif
  14. #include "opencv2/core.hpp"
  15. #include "opencv2/core/opengl.hpp"
  16. #include "opencv2/core/cuda.hpp"
  17. #include "opencv2/highgui.hpp"
  18. using namespace std;
  19. using namespace cv;
  20. using namespace cv::cuda;
  21. const int win_width = 800;
  22. const int win_height = 640;
  23. struct DrawData
  24. {
  25. ogl::Arrays arr;
  26. ogl::Texture2D tex;
  27. ogl::Buffer indices;
  28. };
  29. void draw(void* userdata);
  30. void draw(void* userdata)
  31. {
  32. DrawData* data = static_cast<DrawData*>(userdata);
  33. glRotated(0.6, 0, 1, 0);
  34. ogl::render(data->arr, data->indices, ogl::TRIANGLES);
  35. }
  36. int main(int argc, char* argv[])
  37. {
  38. string filename;
  39. if (argc < 2)
  40. {
  41. cout << "Usage: " << argv[0] << " image" << endl;
  42. filename = "lena.jpg";
  43. }
  44. else
  45. filename = argv[1];
  46. Mat img = imread(samples::findFile(filename));
  47. if (img.empty())
  48. {
  49. cerr << "Can't open image " << filename << endl;
  50. return -1;
  51. }
  52. namedWindow("OpenGL", WINDOW_OPENGL);
  53. resizeWindow("OpenGL", win_width, win_height);
  54. Mat_<Vec2f> vertex(1, 4);
  55. vertex << Vec2f(-1, 1), Vec2f(-1, -1), Vec2f(1, -1), Vec2f(1, 1);
  56. Mat_<Vec2f> texCoords(1, 4);
  57. texCoords << Vec2f(0, 0), Vec2f(0, 1), Vec2f(1, 1), Vec2f(1, 0);
  58. Mat_<int> indices(1, 6);
  59. indices << 0, 1, 2, 2, 3, 0;
  60. DrawData data;
  61. data.arr.setVertexArray(vertex);
  62. data.arr.setTexCoordArray(texCoords);
  63. data.indices.copyFrom(indices);
  64. data.tex.copyFrom(img);
  65. glMatrixMode(GL_PROJECTION);
  66. glLoadIdentity();
  67. gluPerspective(45.0, (double)win_width / win_height, 0.1, 100.0);
  68. glMatrixMode(GL_MODELVIEW);
  69. glLoadIdentity();
  70. gluLookAt(0, 0, 3, 0, 0, 0, 0, 1, 0);
  71. glEnable(GL_TEXTURE_2D);
  72. data.tex.bind();
  73. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  74. glTexEnvi(GL_TEXTURE_2D, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  75. glDisable(GL_CULL_FACE);
  76. setOpenGlDrawCallback("OpenGL", draw, &data);
  77. for (;;)
  78. {
  79. updateWindow("OpenGL");
  80. char key = (char)waitKey(40);
  81. if (key == 27)
  82. break;
  83. }
  84. setOpenGlDrawCallback("OpenGL", 0, 0);
  85. destroyAllWindows();
  86. return 0;
  87. }