我正在开发一个项目,该项目使用opencv来检测屏幕上的一些图像并获取它们的坐标。我在stackoverflow上找到了一个快速截取屏幕截图的功能,因此我可以非常快速地扫描屏幕。这是代码:
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <cstdint>
#include <cstring>
#include <vector>
#include "/usr/local/include/opencv2/opencv.hpp"
using namespace cv;
//Function to take screenshots, this is the function that seems to be causing the HDD thrashing
void ImageFromDisplay(std::vector<uint8_t>& Pixels, int& Width, int& Height, int& BitsPerPixel)
{
Display* display = XOpenDisplay(nullptr);
Window root = DefaultRootWindow(display);
XWindowAttributes attributes = {0};
XGetWindowAttributes(display, root, &attributes);
Width = attributes.width;
Height = attributes.height;
XImage* img = XGetImage(display, root, 0, 0 , Width, Height, AllPlanes, ZPixmap);
BitsPerPixel = img->bits_per_pixel;
Pixels.resize(Width * Height * 4);
memcpy(&Pixels[0], img->data, Pixels.size());
XFree(img);
XCloseDisplay(display);
}
int main(){
int Width = 0;
int Height = 0;
int Bpp = 0;
std::vector<std::uint8_t> Pixels;
while (1){
//Func to take image (this is what is causing the thrashing)
ImageFromDisplay(Pixels, Width, Height, Bpp);
if (Width && Height){
//Create a matrix
Mat img = Mat(Height, Width, Bpp > 24 ? CV_8UC4 : CV_8UC3, &Pixels[0]);
//Display matrix
imshow("Display window", img);
waitKey(1);
}
}
}
我没有使用X11的经验,所以我不知道如何解决这个问题。谁能告诉我究竟是什么导致了颠簸,我该如何解决?