opencv获取usb摄像头呃名字
时间: 2024-06-02 10:06:52 浏览: 154
要获取 USB 摄像头的名称,可以使用 OpenCV 中的 VideoCapture 类。以下是获取 USB 摄像头名称的示例代码:
```
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
int camera_id = 0;
VideoCapture cap(camera_id);
if (!cap.isOpened())
{
cerr << "ERROR: Unable to open the camera" << endl;
return 1;
}
// Get the camera name
string camera_name = "";
cap.set(CAP_PROP_SETTINGS, 1); // Open the camera properties dialog
cap.set(CAP_PROP_SETTINGS, 0); // Close the camera properties dialog
cap.set(CAP_PROP_SETTINGS, 1); // Open the camera properties dialog
cap.set(CAP_PROP_SETTINGS, 0); // Close the camera properties dialog
cap.set(CAP_PROP_SETTINGS, 1); // Open the camera properties dialog
cap.set(CAP_PROP_SETTINGS, 0); // Close the camera properties dialog
cap.set(CAP_PROP_SETTINGS, 1); // Open the camera properties dialog
cap.set(CAP_PROP_SETTINGS, 0); // Close the camera properties dialog
cap >> Mat(); // Release the camera buffer
cap >> Mat(); // Release the camera buffer
cap >> Mat(); // Release the camera buffer
cap >> Mat(); // Release the camera buffer
cap >> Mat(); // Release the camera buffer
cap >> Mat(); // Release the camera buffer
cap >> Mat(); // Release the camera buffer
cap >> Mat(); // Release the camera buffer
cap >> Mat(); // Release the camera buffer
cap >> Mat(); // Release the camera buffer
cap >> Mat(); // Release the camera buffer
cap >> Mat(); // Release the camera buffer
cap >> Mat(); // Release the camera buffer
int prop_id = CAP_PROP_FOURCC;
int fourcc = static_cast<int>(cap.get(prop_id));
if (fourcc == static_cast<int>(CAP_FFMPEG))
{
prop_id = CAP_PROP_BACKEND;
int backend_id = static_cast<int>(cap.get(prop_id));
if (backend_id == static_cast<int>(CAP_BACKEND_V4L2))
{
prop_id = CAP_PROP_V4L2_CAPS;
string v4l2_caps = cap.get(prop_id);
size_t name_start_pos = v4l2_caps.find("card=");
if (name_start_pos != string::npos)
{
name_start_pos += strlen("card=");
size_t name_end_pos = v4l2_caps.find(",", name_start_pos);
if (name_end_pos != string::npos)
{
camera_name = v4l2_caps.substr(name_start_pos, name_end_pos - name_start_pos);
}
else
{
camera_name = v4l2_caps.substr(name_start_pos);
}
}
}
else if (backend_id == static_cast<int>(CAP_BACKEND_MSMF))
{
prop_id = CAP_PROP_MSMF_DEVICE_NAME;
camera_name = cap.get(prop_id);
}
else if (backend_id == static_cast<int>(CAP_BACKEND_DSHOW))
{
prop_id = CAP_PROP_DSHOW_DEVICE_NAME;
camera_name = cap.get(prop_id);
}
else if (backend_id == static_cast<int>(CAP_BACKEND_AVFOUNDATION))
{
prop_id = CAP_PROP_AVFOUNDATION_VIDEO_DEVICE_NAME;
camera_name = cap.get(prop_id);
}
}
cout << "Camera Name: " << camera_name << endl;
return 0;
}
```
此代码使用 `VideoCapture` 类打开摄像头,并通过 `set` 函数打开和关闭摄像头属性对话框。然后,它检索摄像头的名称并将其打印到控制台上。
阅读全文