如何使用 C++ 中的 OpenCV 從其他攝像機捕獲影片?


在本主題中,我們將確定如何使用 OpenCV 從其他攝像機捕獲影片。訪問除預設攝像機外的其他攝像機與訪問預設攝像機類似。僅有一點不同,即我們必須分配攝像機號,而不是使用“VideoCapture cap(0)”。攝像機號根據 USB 埠的順序確定。如果攝像機連線到第三個 USB 埠,則攝像機號為 3。

以下程式訪問第三個攝像機,並顯示從攝像機獲取的即時影片流。

示例

#include<opencv2/opencv.hpp>//OpenCV header to use VideoCapture class//
#include<iostream>
using namespace std;
using namespace cv;
int main() {
   Mat myImage;//Declaring a matrix to load the frames//
   namedWindow("Video Player");//Declaring the video to show the video//
   VideoCapture cap(3);//Declaring an object to capture stream of frames from third camera//
   if (!cap.isOpened()){ //This section prompt an error message if no video stream is found//
      cout << "No video stream detected" << endl;
      system("pause");
      return-1;
   }
   while (true){ //Taking an everlasting loop to show the video//
      cap >> myImage;
      if (myImage.empty()){ //Breaking the loop if no video frame is detected//
         break;
      }
      imshow("Video Player", myImage);//Showing the video//
      char c = (char)waitKey(25);//Allowing 25 milliseconds frame processing time and initiating break condition//
      if (c == 27){ //If 'Esc' is entered break the loop//
         break;
      }
      imshow("Video Player", myImage);//Showing the video//
      char c = (char)waitKey(25);//Allowing 25 milliseconds frame processing time and initiating break condition//
      if (c == 27){ //If 'Esc' is entered break the loop//
         break;
      }
   }
   cap.release();//Releasing the buffer memory//
   return 0;
}

輸出

更新於:2021 年 3 月 10 日

3 千次+ 瀏覽

開啟您的 職業生涯

透過完成本課程獲得認證

開始
廣告
© . All rights reserved.