2021年8月20日 星期五

linux 上使用 opencv 抓取螢幕影像

 不囉唆, 直接看原始碼 x1.cpp:
#include <opencv2/opencv.hpp>
#include <X11/Xutil.h>
#include <stdio.h>
using namespace std;
int main(int argc, char ** argv){
    XWindowAttributes x = { 0 };// x window 屬性(參數群)
    auto display = XOpenDisplay(nullptr);   // 打開 x window server 的顯示器
    auto root = DefaultRootWindow(display); // get default root?
    XGetWindowAttributes(display, root, &x);// 取得螢幕參數
    int height = x.height;
    int width  = x.width;
    auto buffer = XGetImage(display, root,
        0, 0, width, height,
        AllPlanes, ZPixmap
    );// 全螢幕影像

    int cvType = CV_8UC4;// default 4 bytes's A,R,G,B
    switch (buffer->bits_per_pixel) {
        case 24: cvType = CV_8UC3; break;// 3 bytes
        case 16: cvType = CV_8UC2; break;// 2 bytes
        case  8: cvType = CV_8UC1; break;// 1 bytes
    }
    const char *name = "ScreenCapture";
    cv::namedWindow(name, cv::WINDOW_AUTOSIZE);
    cv::Mat m(height, width, cvType, buffer->data);  // 暫時包成 cv::Mat
    cv::imshow(name, m); // 顯示全螢幕影像

    cv::resize(m, m, cv::Size(), 0.25, 0.25, cv::INTER_LINEAR);// 長寬各縮 1/4
    XDestroyImage(buffer) ;// 釋放 buffer
    XCloseDisplay(display);// 關閉 x window session

    cv::imshow("1/16 Screen Shot", m); // 顯示 1/16 螢幕影像
    cv::waitKey(0);
}
用 g++ 編譯並執行程式:
     g++  x1.cpp  -lX11 `pkg-config  --cflags  --libs  opencv4`  &&  ./a.out

沒有留言:

張貼留言

使用 vscode 時, 改善滑鼠反應遲鈍的問題

按下 Manage 按鈕 Settings, 輸入 server, 儘量避免選項被啟用, 讓選項儘量 disable 或 off 例如: Http: Proxy Strict SSL 不要勾選 C_Cpp: Code Folding  選擇 disable  C_Cpp: Sug...