使用OpenCV和C++在按键上截取网络摄像头源的屏幕截图

Take screenshot of webcam feed on Keypress using OpenCV and C++

本文关键字:网络 截取 摄像头 屏幕截图 OpenCV C++ 使用      更新时间:2023-10-16

我目前正在使用VideoCapture cap(0(函数获取笔记本电脑的网络摄像头源,然后将其显示在Mat框架中。我接下来要做的是,例如,每当我按下键"c"时,它都会截取帧的屏幕截图并将其作为 JPEG 图像保存到文件夹中。但是我不知道该怎么做。非常需要帮助,谢谢。

我花了几天时间在互联网上搜索简单的键盘输入的正确解决方案。在使用cv::waitKey时,总是有一些腿/延迟。

我找到的解决方案是在从网络摄像头捕获帧后立即添加 Sleep(5(。

下面的示例是不同论坛主题的组合。

它没有任何腿/延迟即可工作。视窗操作系统。

按"q"捕获并保存帧。

始终存在网络摄像头源。您可以更改序列以显示捕获的帧/图像。

PS"tipka" - 在键盘上表示"键"。

问候,安德烈·

#include <opencv2/opencv.hpp>
#include <iostream>
#include <stdio.h>
#include <windows.h> // For Sleep

using namespace cv;
using namespace std;

int ct = 0; 
char tipka;
char filename[100]; // For filename
int  c = 1; // For filename
int main(int, char**)
{

    Mat frame;
    //--- INITIALIZE VIDEOCAPTURE
    VideoCapture cap;
    // open the default camera using default API
    cap.open(0);
    // OR advance usage: select any API backend
    int deviceID = 0;             // 0 = open default camera   
    int apiID = cv::CAP_ANY;      // 0 = autodetect default API
                                  // open selected camera using selected API
    cap.open(deviceID + apiID);
    // check if we succeeded
    if (!cap.isOpened()) {
        cerr << "ERROR! Unable to open cameran";
        return -1;
    }
    //--- GRAB AND WRITE LOOP
    cout << "Start grabbing" << endl
        << "Press a to terminate" << endl;
    for (;;)
    {
        // wait for a new frame from camera and store it into 'frame'
        cap.read(frame);
        if (frame.empty()) {
            cerr << "ERROR! blank frame grabbedn";
            break;
        }

        Sleep(5); // Sleep is mandatory - for no leg!

        // show live and wait for a key with timeout long enough to show images
        imshow("CAMERA 1", frame);  // Window name

        tipka = cv::waitKey(30);

        if (tipka == 'q') {
            sprintf_s(filename, "C:/Images/Frame_%d.jpg", c); // select your folder - filename is "Frame_n"
            cv::waitKey(10); 
            imshow("CAMERA 1", frame);
            imwrite(filename, frame);
            cout << "Frame_" << c << endl;
            c++;
        }

        if (tipka == 'a') {
            cout << "Terminating..." << endl;
            Sleep(2000);
            break;
        }

    }
    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}