opencv怎么获取摄像头名称并打开相应的摄像头
时间: 2023-05-21 14:00:50 浏览: 78
可以使用opencv中的VideoCapture类来获取摄像头名称并打开相应的摄像头。具体的代码如下:
```
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 获取摄像头列表
vector<VideoCapture> cameras;
for (int i = 0; i < 10; i++)
{
VideoCapture cap(i);
if (cap.isOpened())
{
cameras.push_back(cap);
cout << "Camera " << i << " is opened." << endl;
}
}
// 打开指定的摄像头
int cameraIndex = 0; // 指定摄像头的索引
if (cameraIndex >= cameras.size())
{
cout << "Camera " << cameraIndex << " is not available." << endl;
return -1;
}
VideoCapture cap = cameras[cameraIndex];
if (!cap.isOpened())
{
cout << "Failed to open camera " << cameraIndex << "." << endl;
return -1;
}
// 读取摄像头数据
Mat frame;
while (true)
{
cap >> frame;
if (frame.empty())
{
cout << "Failed to read frame." << endl;
break;
}
imshow("Camera", frame);
if (waitKey(30) == 27) // 按下ESC键退出
{
break;
}
}
return 0;
}
```
在上面的代码中,我们首先使用VideoCapture类获取所有可用的摄像头,并打印出它们的索引。然后,我们可以指定要打开的摄像头的索引,如果该摄像头不可用,则会提示错误信息。最后,我们使用while循环读取摄像头数据,并在窗口中显示。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)