windows下使用camera(opencv方式)

  一.  opencv支持读取摄像头,支持视频录制或显示, 具体代码

    //1. 初始化视频录制文件
    String recFileName = std::to_string(count) + "_rec.avi";
    int wfourcc = VideoWriter::fourcc('M', 'J', 'P', 'G');
    writer = VideoWriter(recFileName, wfourcc, CAP_FPS, Size(CAP_WIDTH, CAP_HEIGHT));

    //2. 初始化摄像头
    int apiBackend = CAP_DSHOW;
    cap = VideoCapture(count + apiBackend);

    //cap.set(CAP_PROP_SETTINGS, 1);
    int w = cap.get(CAP_PROP_FRAME_WIDTH);
    int h = cap.get(CAP_PROP_FRAME_HEIGHT);    
    int fourcc = cap.get(CAP_PROP_FOURCC);
    qDebug() << "camera origin parameters: fourcc:" << fourcc<<", width: "<

    cap.set(CAP_PROP_FRAME_WIDTH, CAP_WIDTH);
    cap.set(CAP_PROP_FRAME_HEIGHT, CAP_HEIGHT);
    cap.set(CAP_PROP_FOURCC, VideoWriter::fourcc('M', 'J', 'P', 'G'));
    //cap.set(CAP_PROP_FOURCC, VideoWriter::fourcc('H', '2', '6', '4'));
    
    w = cap.get(CAP_PROP_FRAME_WIDTH);
    h = cap.get(CAP_PROP_FRAME_HEIGHT);
    fourcc = cap.get(CAP_PROP_FOURCC);
    qDebug() << "camera modified parameters: fourcc:" << fourcc << ", width: " << w << ", height:" << h;
    
    cap.set(CAP_PROP_FOCUS, 0);
    //cap.set(CAP_PROP_FPS, CAP_FPS);    
    //cap.set(CAP_PROP_BACKLIGHT, 1);
    
    if (!cap.isOpened())
    {
        QString massage = QString("camera %1 opens fail!").arg(count);
        qDebug() << massage;
        return;
    }
    else {
        qDebug() << "camera " << count << " start successfully!";
    }

   //3. 循环读取摄像头帧内容,并用opencv的imshow展示

    while (cap.isOpened() && captureEnabled) {                
        Mat img;
        QString begin_time = QDateTime::currentDateTime().toString("hh:mm:ss.zzz");

        cap >> img;
        QString captured_time = QDateTime::currentDateTime().toString("hh:mm:ss.zzz");

        if (!img.cols || !img.rows) {
            qDebug() << "Error thread " << count << ", begin time: " << begin_time << ", captured_time: " << captured_time;
            continue;
        }

        if (recordEnabled) {
            writer << img;
        }

        QString write_time = QDateTime::currentDateTime().toString("hh:mm:ss.zzz");

        Mat img_dst;
        cv::resize(img, img_dst, cv::Size(CAP_WIDTH / 2, CAP_HEIGHT / 2), 0, 0, cv::INTER_AREA);

#if 0   //4. 发送到其它UI线程做显示
        QImage image = Mat2QImage(img_dst);
        emit thread_update_image(count, image);
#else //4. 直接用opencv的imshow做显示
        String captureWindow = "capture_win_" + std::to_string(count);
        imshow(captureWindow, img_dst);
        int waitTimeMs = 1000 / CAP_FPS - 10;  //encode consume 10 ms
        waitKey(waitTimeMs);
#endif
    }

    //5. 关闭摄像头,释放recorder

    if (!captureEnabled) {
        QString current_time = QDateTime::currentDateTime().toString("hh:mm:ss.zzz");
        qDebug() << "thread " << count << ", close capture and writer, at time : " << current_time;
        writer.release();
        cap.release();
    }
 

你可能感兴趣的:(ffmpeg)