Opencv视频捕捉c++不工作2次

opencv videocapture c++ not working 2 times

本文关键字:工作 2次 c++ 视频 Opencv      更新时间:2023-10-16

我尝试了以下代码来从我的网络摄像头捕获视频:

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace cv;
using namespace std;
int main()
{
    VideoCapture cap(0); // open the video camera no. 0
    if (!cap.isOpened())  // if not success, exit program
    {
        cout << "Cannot open the video cam" << endl;
        return -1;
    }

    double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video
    double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video
    cout << "Frame size : " << dWidth << " x " << dHeight << endl;
    namedWindow("MyVideo", CV_WINDOW_AUTOSIZE); //create a window called "MyVideo"
    namedWindow("Changed", CV_WINDOW_AUTOSIZE);
    while (1)
    {
        Mat frame;
        bool bSuccess = cap.read(frame); // read a new frame from video
        if (!bSuccess) //if not success, break loop
        {
            cout << "Cannot read a frame from video stream" << endl;
            break;
        }
        Mat imgH = frame + Scalar(75, 75, 75);
        imshow("MyVideo", frame); //show the frame in "MyVideo" window
        imshow("Changed", imgH);
        if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
        {
            cout << "esc key is pressed by user" << endl;
            break;
        }
    }
    return 0;
}

现在我的问题是:第一次调试那个程序后,一切都如预期的那样工作。但是当第二次调试时(在修改代码中的一些行之后),它不能从相机读取。

有谁能给我一个提示如何解决那个问题吗?

谢谢!

您发布的代码似乎在我的情况下工作绝对很好,输出是预期的。但是,请确保在运行程序之前打开您的网络摄像头,这一点很重要。由于我的计算机中有一个用于网络摄像头的YouCam客户端,因此它显示我需要启动YouCam。

由于我没有足够的声誉来发布图像,所以请参阅以下链接,以便查看我在网络摄像头尚未打开时得到的输出

https://i.stack.imgur.com/vGXGw.png

希望这有帮助!!