opengl_interop.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. /*
  2. // Sample demonstrating interoperability of OpenCV UMat with OpenGL texture.
  3. // At first, the data obtained from video file or camera and placed onto
  4. // OpenGL texture, following mapping of this OpenGL texture to OpenCV UMat
  5. // and call cv::Blur function. The result is mapped back to OpenGL texture
  6. // and rendered through OpenGL API.
  7. */
  8. #if defined(_WIN32)
  9. # define WIN32_LEAN_AND_MEAN
  10. # include <windows.h>
  11. #elif defined(__linux__)
  12. # include <X11/X.h>
  13. # include <X11/Xlib.h>
  14. #endif
  15. #include <iostream>
  16. #include <queue>
  17. #include <string>
  18. #include <stdio.h>
  19. #include "opencv2/core.hpp"
  20. #include "opencv2/core/opengl.hpp"
  21. #include "opencv2/core/ocl.hpp"
  22. #include "opencv2/imgproc.hpp"
  23. #include "opencv2/videoio.hpp"
  24. #include "winapp.hpp"
  25. #if defined(_WIN32)
  26. # pragma comment(lib, "opengl32.lib")
  27. # pragma comment(lib, "glu32.lib")
  28. #endif
  29. class GLWinApp : public WinApp
  30. {
  31. public:
  32. enum MODE
  33. {
  34. MODE_CPU = 0,
  35. MODE_GPU
  36. };
  37. GLWinApp(int width, int height, std::string& window_name, cv::VideoCapture& cap) :
  38. WinApp(width, height, window_name)
  39. {
  40. m_shutdown = false;
  41. m_use_buffer = false;
  42. m_demo_processing = true;
  43. m_mode = MODE_CPU;
  44. m_modeStr[0] = cv::String("Processing on CPU");
  45. m_modeStr[1] = cv::String("Processing on GPU");
  46. m_cap = cap;
  47. }
  48. ~GLWinApp() {}
  49. virtual void cleanup() CV_OVERRIDE
  50. {
  51. m_shutdown = true;
  52. #if defined(__linux__)
  53. glXMakeCurrent(m_display, None, NULL);
  54. glXDestroyContext(m_display, m_glctx);
  55. #endif
  56. WinApp::cleanup();
  57. }
  58. #if defined(_WIN32)
  59. virtual LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) CV_OVERRIDE
  60. {
  61. switch (message)
  62. {
  63. case WM_CHAR:
  64. if (wParam == '1')
  65. {
  66. set_mode(MODE_CPU);
  67. return EXIT_SUCCESS;
  68. }
  69. if (wParam == '2')
  70. {
  71. set_mode(MODE_GPU);
  72. return EXIT_SUCCESS;
  73. }
  74. else if (wParam == '9')
  75. {
  76. toggle_buffer();
  77. return EXIT_SUCCESS;
  78. }
  79. else if (wParam == VK_SPACE)
  80. {
  81. m_demo_processing = !m_demo_processing;
  82. return EXIT_SUCCESS;
  83. }
  84. else if (wParam == VK_ESCAPE)
  85. {
  86. cleanup();
  87. return EXIT_SUCCESS;
  88. }
  89. break;
  90. case WM_CLOSE:
  91. cleanup();
  92. return EXIT_SUCCESS;
  93. case WM_DESTROY:
  94. ::PostQuitMessage(0);
  95. return EXIT_SUCCESS;
  96. }
  97. return ::DefWindowProc(hWnd, message, wParam, lParam);
  98. }
  99. #endif
  100. #if defined(__linux__)
  101. int handle_event(XEvent& e) CV_OVERRIDE
  102. {
  103. switch(e.type)
  104. {
  105. case ClientMessage:
  106. if ((Atom)e.xclient.data.l[0] == m_WM_DELETE_WINDOW)
  107. {
  108. m_end_loop = true;
  109. cleanup();
  110. }
  111. else
  112. {
  113. return EXIT_SUCCESS;
  114. }
  115. break;
  116. case Expose:
  117. render();
  118. break;
  119. case KeyPress:
  120. switch(keycode_to_keysym(e.xkey.keycode))
  121. {
  122. case XK_space:
  123. m_demo_processing = !m_demo_processing;
  124. break;
  125. case XK_1:
  126. set_mode(MODE_CPU);
  127. break;
  128. case XK_2:
  129. set_mode(MODE_GPU);
  130. break;
  131. case XK_9:
  132. toggle_buffer();
  133. break;
  134. case XK_Escape:
  135. m_end_loop = true;
  136. cleanup();
  137. break;
  138. }
  139. break;
  140. default:
  141. return EXIT_SUCCESS;
  142. }
  143. return 1;
  144. }
  145. #endif
  146. int init() CV_OVERRIDE
  147. {
  148. #if defined(_WIN32)
  149. m_hDC = GetDC(m_hWnd);
  150. if (setup_pixel_format() != 0)
  151. {
  152. std::cerr << "Can't setup pixel format" << std::endl;
  153. return EXIT_FAILURE;
  154. }
  155. m_hRC = wglCreateContext(m_hDC);
  156. wglMakeCurrent(m_hDC, m_hRC);
  157. #elif defined(__linux__)
  158. m_glctx = glXCreateContext(m_display, m_visual_info, NULL, GL_TRUE);
  159. glXMakeCurrent(m_display, m_window, m_glctx);
  160. #endif
  161. glEnable(GL_TEXTURE_2D);
  162. glEnable(GL_DEPTH_TEST);
  163. glViewport(0, 0, m_width, m_height);
  164. if (cv::ocl::haveOpenCL())
  165. {
  166. (void) cv::ogl::ocl::initializeContextFromGL();
  167. }
  168. m_oclDevName = cv::ocl::useOpenCL() ?
  169. cv::ocl::Context::getDefault().device(0).name() :
  170. (char*) "No OpenCL device";
  171. return EXIT_SUCCESS;
  172. } // init()
  173. int get_frame(cv::ogl::Texture2D& texture, cv::ogl::Buffer& buffer, bool do_buffer)
  174. {
  175. if (!m_cap.read(m_frame_bgr))
  176. return EXIT_FAILURE;
  177. cv::cvtColor(m_frame_bgr, m_frame_rgba, cv::COLOR_RGB2RGBA);
  178. if (do_buffer)
  179. buffer.copyFrom(m_frame_rgba, cv::ogl::Buffer::PIXEL_UNPACK_BUFFER, true);
  180. else
  181. texture.copyFrom(m_frame_rgba, true);
  182. return EXIT_SUCCESS;
  183. }
  184. void print_info(MODE mode, double time, cv::String& oclDevName)
  185. {
  186. #if defined(_WIN32)
  187. HDC hDC = m_hDC;
  188. HFONT hFont = (HFONT)::GetStockObject(SYSTEM_FONT);
  189. HFONT hOldFont = (HFONT)::SelectObject(hDC, hFont);
  190. if (hOldFont)
  191. {
  192. TEXTMETRIC tm;
  193. ::GetTextMetrics(hDC, &tm);
  194. char buf[256+1];
  195. int y = 0;
  196. buf[0] = 0;
  197. sprintf_s(buf, sizeof(buf)-1, "Mode: %s OpenGL %s", m_modeStr[mode].c_str(), use_buffer() ? "buffer" : "texture");
  198. ::TextOut(hDC, 0, y, buf, (int)strlen(buf));
  199. y += tm.tmHeight;
  200. buf[0] = 0;
  201. sprintf_s(buf, sizeof(buf)-1, "Time, msec: %2.1f", time);
  202. ::TextOut(hDC, 0, y, buf, (int)strlen(buf));
  203. y += tm.tmHeight;
  204. buf[0] = 0;
  205. sprintf_s(buf, sizeof(buf)-1, "OpenCL device: %s", oclDevName.c_str());
  206. ::TextOut(hDC, 0, y, buf, (int)strlen(buf));
  207. ::SelectObject(hDC, hOldFont);
  208. }
  209. #elif defined(__linux__)
  210. char buf[256+1];
  211. snprintf(buf, sizeof(buf)-1, "Time, msec: %2.1f, Mode: %s OpenGL %s, Device: %s", time, m_modeStr[mode].c_str(), use_buffer() ? "buffer" : "texture", oclDevName.c_str());
  212. XStoreName(m_display, m_window, buf);
  213. #endif
  214. }
  215. void idle() CV_OVERRIDE
  216. {
  217. render();
  218. }
  219. int render() CV_OVERRIDE
  220. {
  221. try
  222. {
  223. if (m_shutdown)
  224. return EXIT_SUCCESS;
  225. int r;
  226. cv::ogl::Texture2D texture;
  227. cv::ogl::Buffer buffer;
  228. texture.setAutoRelease(true);
  229. buffer.setAutoRelease(true);
  230. MODE mode = get_mode();
  231. bool do_buffer = use_buffer();
  232. r = get_frame(texture, buffer, do_buffer);
  233. if (r != 0)
  234. {
  235. return EXIT_FAILURE;
  236. }
  237. switch (mode)
  238. {
  239. case MODE_CPU: // process frame on CPU
  240. processFrameCPU(texture, buffer, do_buffer);
  241. break;
  242. case MODE_GPU: // process frame on GPU
  243. processFrameGPU(texture, buffer, do_buffer);
  244. break;
  245. } // switch
  246. if (do_buffer) // buffer -> texture
  247. {
  248. cv::Mat m(m_height, m_width, CV_8UC4);
  249. buffer.copyTo(m);
  250. texture.copyFrom(m, true);
  251. }
  252. #if defined(__linux__)
  253. XWindowAttributes window_attributes;
  254. XGetWindowAttributes(m_display, m_window, &window_attributes);
  255. glViewport(0, 0, window_attributes.width, window_attributes.height);
  256. #endif
  257. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  258. glLoadIdentity();
  259. glEnable(GL_TEXTURE_2D);
  260. texture.bind();
  261. glBegin(GL_QUADS);
  262. glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 0.1f);
  263. glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, -1.0f, 0.1f);
  264. glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, -1.0f, 0.1f);
  265. glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, 1.0f, 0.1f);
  266. glEnd();
  267. #if defined(_WIN32)
  268. SwapBuffers(m_hDC);
  269. #elif defined(__linux__)
  270. glXSwapBuffers(m_display, m_window);
  271. #endif
  272. print_info(mode, m_timer.getTimeMilli(), m_oclDevName);
  273. }
  274. catch (const cv::Exception& e)
  275. {
  276. std::cerr << "Exception: " << e.what() << std::endl;
  277. return 10;
  278. }
  279. return EXIT_SUCCESS;
  280. }
  281. protected:
  282. void processFrameCPU(cv::ogl::Texture2D& texture, cv::ogl::Buffer& buffer, bool do_buffer)
  283. {
  284. cv::Mat m(m_height, m_width, CV_8UC4);
  285. m_timer.reset();
  286. m_timer.start();
  287. if (do_buffer)
  288. buffer.copyTo(m);
  289. else
  290. texture.copyTo(m);
  291. if (m_demo_processing)
  292. {
  293. // blur texture image with OpenCV on CPU
  294. cv::blur(m, m, cv::Size(15, 15));
  295. }
  296. if (do_buffer)
  297. buffer.copyFrom(m, cv::ogl::Buffer::PIXEL_UNPACK_BUFFER, true);
  298. else
  299. texture.copyFrom(m, true);
  300. m_timer.stop();
  301. }
  302. void processFrameGPU(cv::ogl::Texture2D& texture, cv::ogl::Buffer& buffer, bool do_buffer)
  303. {
  304. cv::UMat u;
  305. m_timer.reset();
  306. m_timer.start();
  307. if (do_buffer)
  308. u = cv::ogl::mapGLBuffer(buffer);
  309. else
  310. cv::ogl::convertFromGLTexture2D(texture, u);
  311. if (m_demo_processing)
  312. {
  313. // blur texture image with OpenCV on GPU with OpenCL
  314. cv::blur(u, u, cv::Size(15, 15));
  315. }
  316. if (do_buffer)
  317. cv::ogl::unmapGLBuffer(u);
  318. else
  319. cv::ogl::convertToGLTexture2D(u, texture);
  320. m_timer.stop();
  321. }
  322. #if defined(_WIN32)
  323. int setup_pixel_format()
  324. {
  325. PIXELFORMATDESCRIPTOR pfd;
  326. pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
  327. pfd.nVersion = 1;
  328. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  329. pfd.iPixelType = PFD_TYPE_RGBA;
  330. pfd.cColorBits = 24;
  331. pfd.cRedBits = 8;
  332. pfd.cRedShift = 0;
  333. pfd.cGreenBits = 8;
  334. pfd.cGreenShift = 0;
  335. pfd.cBlueBits = 8;
  336. pfd.cBlueShift = 0;
  337. pfd.cAlphaBits = 8;
  338. pfd.cAlphaShift = 0;
  339. pfd.cAccumBits = 0;
  340. pfd.cAccumRedBits = 0;
  341. pfd.cAccumGreenBits = 0;
  342. pfd.cAccumBlueBits = 0;
  343. pfd.cAccumAlphaBits = 0;
  344. pfd.cDepthBits = 24;
  345. pfd.cStencilBits = 8;
  346. pfd.cAuxBuffers = 0;
  347. pfd.iLayerType = PFD_MAIN_PLANE;
  348. pfd.bReserved = 0;
  349. pfd.dwLayerMask = 0;
  350. pfd.dwVisibleMask = 0;
  351. pfd.dwDamageMask = 0;
  352. int pfmt = ChoosePixelFormat(m_hDC, &pfd);
  353. if (pfmt == 0)
  354. return EXIT_FAILURE;
  355. if (SetPixelFormat(m_hDC, pfmt, &pfd) == 0)
  356. return -2;
  357. return EXIT_SUCCESS;
  358. }
  359. #endif
  360. #if defined(__linux__)
  361. KeySym keycode_to_keysym(unsigned keycode)
  362. { // note that XKeycodeToKeysym() is considered deprecated
  363. int keysyms_per_keycode_return = 0;
  364. KeySym *keysyms = XGetKeyboardMapping(m_display, keycode, 1, &keysyms_per_keycode_return);
  365. KeySym keysym = keysyms[0];
  366. XFree(keysyms);
  367. return keysym;
  368. }
  369. #endif
  370. bool use_buffer() { return m_use_buffer; }
  371. void toggle_buffer() { m_use_buffer = !m_use_buffer; }
  372. MODE get_mode() { return m_mode; }
  373. void set_mode(MODE mode) { m_mode = mode; }
  374. private:
  375. bool m_shutdown;
  376. bool m_use_buffer;
  377. bool m_demo_processing;
  378. MODE m_mode;
  379. cv::String m_modeStr[2];
  380. #if defined(_WIN32)
  381. HDC m_hDC;
  382. HGLRC m_hRC;
  383. #elif defined(__linux__)
  384. GLXContext m_glctx;
  385. #endif
  386. cv::VideoCapture m_cap;
  387. cv::Mat m_frame_bgr;
  388. cv::Mat m_frame_rgba;
  389. cv::String m_oclDevName;
  390. };
  391. static const char* keys =
  392. {
  393. "{c camera | 0 | camera id }"
  394. "{f file | | movie file name }"
  395. };
  396. using namespace cv;
  397. using namespace std;
  398. int main(int argc, char** argv)
  399. {
  400. cv::CommandLineParser parser(argc, argv, keys);
  401. int camera_id = parser.get<int>("camera");
  402. string file = parser.get<string>("file");
  403. parser.about(
  404. "\nA sample program demonstrating interoperability of OpenGL and OpenCL with OpenCV.\n\n"
  405. "Hot keys: \n"
  406. " SPACE - turn processing on/off\n"
  407. " 1 - process GL data through OpenCV on CPU\n"
  408. " 2 - process GL data through OpenCV on GPU (via OpenCL)\n"
  409. " 9 - toggle use of GL texture/GL buffer\n"
  410. " ESC - exit\n\n");
  411. parser.printMessage();
  412. cv::VideoCapture cap;
  413. if (file.empty())
  414. cap.open(camera_id);
  415. else
  416. cap.open(file.c_str());
  417. if (!cap.isOpened())
  418. {
  419. printf("can not open camera or video file\n");
  420. return EXIT_FAILURE;
  421. }
  422. int width = (int)cap.get(CAP_PROP_FRAME_WIDTH);
  423. int height = (int)cap.get(CAP_PROP_FRAME_HEIGHT);
  424. #if defined(_WIN32)
  425. string wndname = "WGL Window";
  426. #elif defined(__linux__)
  427. string wndname = "GLX Window";
  428. #endif
  429. GLWinApp app(width, height, wndname, cap);
  430. try
  431. {
  432. app.create();
  433. return app.run();
  434. }
  435. catch (const cv::Exception& e)
  436. {
  437. cerr << "Exception: " << e.what() << endl;
  438. return 10;
  439. }
  440. catch (...)
  441. {
  442. cerr << "FATAL ERROR: Unknown exception" << endl;
  443. return 11;
  444. }
  445. }