ScreenReader.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <opencv2/opencv.hpp>
  2. #include <X11/Xlib.h>
  3. #include <X11/Xutil.h>
  4. ////////////////////////////////////////////////////////////////////////////////
  5. //
  6. // @compile g++ ScreenReader.cpp -o screenReader -lX11 -lXext -Ofast -mfpmath=both -march=native -m64 -funroll-loops -mavx2 `pkg-config --cflags --libs opencv4` && ./screenReader
  7. // @see https://stackoverflow.com/questions/24988164/c-fast-screenshots-in-linux-for-use-with-opencv/39781697
  8. // @see https://github.com/cnlohr/x11framegrab/blob/master/x11framegrab.c
  9. // @todos chatch keystrokes => take screenshot / commandline parameters/ background deamon / beep (optional) / save img with basename + number + format / optional acustic beep
  10. // k9qwfbVuHk9nHCRD2f5N
  11. ////////////////////////////////////////////////////////////////////////////////
  12. class ScreenReader
  13. {
  14. public:
  15. ScreenReader(int x, int y, int width, int height):
  16. x(x),
  17. y(y),
  18. width(width),
  19. height(height)
  20. {
  21. display = XOpenDisplay(nullptr);
  22. root = DefaultRootWindow(display);
  23. }
  24. void operator() (cv::Mat& cvImg)
  25. {
  26. if(img != nullptr)
  27. XDestroyImage(img);
  28. img = XGetImage(display, root, x, y, width, height, AllPlanes, ZPixmap);
  29. cvImg = cv::Mat(height, width, CV_8UC4, img->data);
  30. }
  31. ~ScreenReader()
  32. {
  33. if(img != nullptr)
  34. XDestroyImage(img);
  35. XCloseDisplay(display);
  36. }
  37. private:
  38. Display* display;
  39. Window root;
  40. int x,y,width,height;
  41. XImage* img{nullptr};
  42. };
  43. ////////////////////////////////////////////////////////////////////////////////
  44. //
  45. ////////////////////////////////////////////////////////////////////////////////
  46. int main()
  47. {
  48. //~ ScreenReader screen(0,0,1920,1080);
  49. ScreenReader screen(400,0,500,800);
  50. cv::Mat img;
  51. screen(img);
  52. cv::imshow("img", img);
  53. while(true)
  54. {
  55. char k = cv::waitKey(10);
  56. if (k == 'q') break;
  57. }
  58. }