I\'m trying to find a fast way to take screenshots (as in 30 fps or over) for use with opencv in c++
All the information I\'ve found online either involved windows.h or
I made a faster functor based screenshot code using Brandon's answer:
#include
#include
#include
class ScreenShot
{
Display* display;
Window root;
int x,y,width,height;
XImage* img{nullptr};
public:
ScreenShot(int x, int y, int width, int height):
x(x),
y(y),
width(width),
height(height)
{
display = XOpenDisplay(nullptr);
root = DefaultRootWindow(display);
}
void operator() (cv::Mat& cvImg)
{
if(img != nullptr)
XDestroyImage(img);
img = XGetImage(display, root, x, y, width, height, AllPlanes, ZPixmap);
cvImg = cv::Mat(height, width, CV_8UC4, img->data);
}
~ScreenShot()
{
if(img != nullptr)
XDestroyImage(img);
XCloseDisplay(display);
}
};
And here is how you would use it in a loop (exit by pressing q
):
int main()
{
ScreenShot screen(0,0,1920,1080);
cv::Mat img;
while(true)
{
screen(img);
cv::imshow("img", img);
char k = cv::waitKey(1);
if (k == 'q')
break;
}
}
This is about 39% faster on my machine.